简体   繁体   中英

Android : SharedPreferences not updated

My 2 android applications communicate throught a AIDL file :

Application A <== AIDL ==> Application B (service)

Application A calls methods of Application B (service) that returns some JSON information. However, If user is not logged in application B, null is returned.

(service in application 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;
}

If null is returned, "login" activity in Application B is launched from Application A.

(Aplication A)

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

User log in (Application B), data are saved in SharedPreferences (Application B) and activity is closed (back to Application 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();

When re-trying to call methods of the Application B, login information saved few seconds ago are not available and null is returned.

I have tried without success with prefsEditor.apply() .

If I restart application B, login data will be loaded....

Please let me know if further information are needed. Thank you

After a long struggle, I have at last managed to get my updated preferences.

When calling getSharedPreferences, I use Context.MODE_MULTI_PROCESS flag.

MODE_MULTI_PROCESS

Thank you.

By reading your comment i can give you a quick solution:

The easier way is to simply terminate your activity (A) before calling the login activity inside your service.

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

So that, when you fill in the login form and call back the activity A it will read the new shared preferences!

Since you need to access the shared preference of other application .

You should try :: Android: Retrieving shared preferences of other application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM