0

我有一个类可以控制我的 http 通信,并跟踪 http 会话。我遇到的问题是,我想从几个活动中使用这个类。
到目前为止,我发现的唯一选择是在主视图中将其设为静态,但如果应用程序在辅助视图中放置很长时间,则静态类变为空。我也尝试过使其可打包,但我无法通过我的 CookieStore 或我的 httpContext。这意味着每次我进入视图或离开视图时,我都必须重新对服务器进行身份验证,从而导致大量不必要的流量。

我如何通过 Parcelable 传递对象,或者是否有另一种类型的类扩展允许我创建一个所有 Activity 都可以查看的持久类?

public class JSON implements Parcelable {
private String URL;
private String HOSTNAME;
private Context f_context;
private DefaultHttpClient httpClient;
private CookieStore cookieStore;
private HttpContext httpContext;
protected boolean Authenticated = false;
protected long Authenticate_timeout = 0;

public int describeContents() {
    return 0;
}

public void writeToParcel(Parcel out, int flags) {
    Bundle b = new Bundle();
    b.putString("URL",URL);
    b.putString("HOSTNAME", HOSTNAME);
    b.putBoolean("Authenticated", Authenticated);
    b.putLong("Authenticate_timeout", Authenticate_timeout);
    out.writeBundle(b);
    Object[] o = new Object[4];
    o[0] = httpClient;
    o[1] = cookieStore;
    o[2] = httpContext;
    o[3] = f_context;
    out.writeArray(o);
    }
public static final Parcelable.Creator<JSON> CREATOR = new Parcelable.Creator<JSON>() {
    public JSON createFromParcel(Parcel in) {
        return new JSON(in);
    }

    public JSON[] newArray(int size) {
        return new JSON[size];
    }
};

private JSON(Parcel in) {
    Object[] o = in.readArray(null);
    httpClient = (DefaultHttpClient) o[0];
    cookieStore = (CookieStore) o[1];
    httpContext = (HttpContext) o[2];
    f_context = (Context) o[3];
    Bundle b = in.readBundle();
    URL = b.getString("URL");
    HOSTNAME = b.getString("HOSTNAME");
    Authenticated = b.getBoolean("Authenticated");
    Authenticate_timeout = b.getLong("Authenticate_timeout");
}

public JSON(Context context) {
    f_context = context;
    updateSettings();
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams
            .setConnectionTimeout(myParams, Consts.http_timeout);
    HttpConnectionParams.setSoTimeout(myParams, Consts.http_timeout);
    httpClient = new DefaultHttpClient(myParams);
    cookieStore = new BasicCookieStore();
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}
4

0 回答 0