如何将Cookie存储为持久数据?

时间:2012-12-13 09:41:09

标签: android cookies httpclient

连接到服务器后,我会获得 Cookie 并将其存储在列表中。

在稍后进行连接时,我将这些cookie添加到DefaultHttpClient。

问题是,当应用程序处于后台一段时间后,所有类数据都将丢失,包括DefaultHttpClient

因此我丢失了cookie

有没有办法让DefaultHttpClient永远保持活着?

或存储和使用Cookie的更好方法?

谢谢

1 个答案:

答案 0 :(得分:0)

从cookie中获取它,然后在应用程序被杀死时将其保存在共享的prefferences中(例如onStop方法)。然后在onCreate()上重新加载它。类似的东西:

public class Calc extends Activity {
   public static final String PREFS_NAME = "MyPrefsFile";

   @Override
   protected void onCreate(Bundle state){
      super.onCreate(state);
      . . .

      // Restore preferences
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      String silent = settings.getString("cookie", null);
      if(cookie == null) {
          // first time, get cookie again and save it
      } else {
          // set cookie manually for HTTPClient
      }
   }

   @Override
   protected void onStop(){
      super.onStop();

     // We need an Editor object to make preference changes.
     // All objects are from android.context.Context
     SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
     SharedPreferences.Editor editor = settings.edit();
     editor.putString("cookie", theCookie);

     // Commit the edits!
     editor.commit();
   }
}

(我已经省略了获取和设置cookie的代码,我认为这不是问题)

相关问题