3
인 텐트를 통해 서비스 클래스에 보내려는 클래스가 있습니다 (아래). Parcelable 인터페이스를 구현했지만 객체의 현재 상태를 포함하여 전체 객체를 실제로 보내고 가져 오는 방법을 잘 모르겠습니다.안드로이드에서 Parcelable 클래스를 올바르게 사용하는 방법
@Override
public void writeToParcel(Parcel dest, int flags) {
//I need this to send the entire state of the object
}
그리고 여기
public UrlParamsHelper(Parcel in) {
//I need this to unpack the state of the object
}
특히
이 writeToParcel 기능에서 실제 클래스
/*
* A holder class for URL parameters
*/
public static class UrlParamsHelper implements Parcelable {
private final HttpClient httpClient;
private final HttpParams params = new BasicHttpParams();
private final SchemeRegistry registry = new SchemeRegistry();
private final ThreadSafeClientConnManager manager;
private final Uri.Builder uri = new Uri.Builder();
final HttpHost host;
final String urlPath;
final String hostname;
/*
* @param hostname the hostname ie. http://www.google.com
* @param urlPath the path to the file of interest ie. /getfiles.php
*/
public UrlParamsHelper(final String hostname, final String urlPath) {
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(), 80));
manager = new ThreadSafeClientConnManager(params, registry);
httpClient = new DefaultHttpClient(manager, params);
host = new HttpHost(hostname, 80, "http");
uri.path(urlPath);
this.urlPath = urlPath;
this.hostname = hostname;
}
public UrlParamsHelper(Parcel in) {
//unpack the state
}
public void addQueryString(String key, String value) {
uri.appendQueryParameter(key, value);
}
public HttpGet buildGetQuery() {
return new HttpGet(uri.build().toString());
}
public HttpClient getHttpClient() {
return httpClient;
}
public HttpHost getHttpHost() {
return host;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
//Parcel the entire state of the object
}
//Constructs the parcel again - REQUIRED
public static final Parcelable.Creator<UrlParamsHelper> CREATOR = new Parcelable.Creator<UrlParamsHelper>() {
public UrlParamsHelper createFromParcel(Parcel in) {
return new UrlParamsHelper(in);
}
public UrlParamsHelper[] newArray(int size) {
throw new UnsupportedOperationException();
//return new UrlParamsHelper[size];
}
};
}
문제는 이미 addQueryString을 통해 여러 개의 QueryString을 추가했다는 것입니다. 이 메서드는 이러한 값을 유지하지 않습니다. – jax
글쎄, 제대로 작동하도록 만들었지 만, 클래스를 좀 더 서투른 것으로 수정하여 쿼리 문자열 매개 변수를 직접 추가하는 대신 키 값 쌍을 보유하는 로컬 맵을 작성한 다음이 맵을 직렬화하고 전송합니다 서비스에. 서비스가 buildGetQuery()를 호출하면 전체 맵은 for 루프를 사용하여 Uri에 놓입니다. 이 모든 것이 이처럼 간단한 개체를 보내는 많은 작업처럼 보입니다. 더 좋은 방법이 있는지 아는 사람 있습니까? – jax
아마도 Uri.Builder에 대한 래퍼를 만들어서 Parcelable로 만들 수도 있습니다. 그런 다음 dest.writeParcelable (uri)과 같은 것을 사용할 수 있습니다. 이것이 단순하지 않다는 것을 알고 있습니다. 단지 논리적 블록으로 나누는 데 도움이됩니다. 단순한 사실은 원시 타입과 다른 Parcelables를 소포에 저장할 수 없다는 것입니다. 따라서 AFAIK는 그것을 수행하는 간단한 방법이 아닙니다. – synic