Android:SharedPreferences未更新

时间:2013-11-26 05:57:36

标签: android sharedpreferences aidl

我的2个Android应用程序通过AIDL文件进行通信:

  

申请A< == AIDL ==>申请B(服务)

应用程序A调用返回一些JSON信息的应用程序B(服务)的方法。但是,如果用户未登录应用程序B,则返回null。

(申请B中的服务)

//first : get info
SharedPreferences mPrefs = getSharedPreferences(Consts.SP_NAME, MODE_PRIVATE);
String userId = mPrefs.getString(Consts.PREFS_USER_ID, "");
String userPass = mPrefs.getString(Consts.PREFS_USER_PASS, "");

//then check is valid (remote server)
if (dao.exist (userId, userPass)){
 return "MY_JSON_INFO" ;
}else{
 return false;
}

如果返回null,则应用程序B中的“登录”活动将从应用程序A启动。

(Aplication A)

if(json == null){
  Intent intent = new Intent("jp.app.LOGIN_ACTIVITY");
  startActivity(intent);
}

用户登录(应用程序B),数据保存在SharedPreferences(应用程序B)中,活动关闭(返回应用程序A)。

SharedPreferences mPrefs = a.getSharedPreferences(Consts.SP_NAME, MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();     
prefsEditor.putString(Consts.PREFS_USER_ID, id);
prefsEditor.putString(Consts.PREFS_USER_PASS, pass);
prefsEditor.commit();

当重新尝试调用应用程序B的方法时,几秒钟前保存的登录信息不可用,并返回null。

我试过prefsEditor.apply()没有成功。

如果我重新启动应用程序B,将加载登录数据....

如果需要进一步的信息,请告诉我。 谢谢

3 个答案:

答案 0 :(得分:1)

经过长时间的努力,我终于设法获得了更新后的偏好。

调用getSharedPreferences时,我使用Context.MODE_MULTI_PROCESS标志。

MODE_MULTI_PROCESS

谢谢。

答案 1 :(得分:0)

通过阅读您的评论,我可以为您提供快速解决方案:

更简单的方法是在调用服务中的登录活动之前简单地终止您的活动(A)。

if(json == null){
  Intent intent = new Intent("jp.app.LOGIN_ACTIVITY");
  startActivity(intent);
  this.finish();
}

这样,当您填写登录表单并回调活动A时,它将读取新的共享首选项!

答案 2 :(得分:0)

由于您需要访问其他application的共享偏好设置。

你应该尝试:: Android: Retrieving shared preferences of other application

相关问题