2013-11-26 49 views
0

我2個機器人應用通信throught一個AIDL文件:機器人:SharedPreferences未更新

應用程序A < == AIDL ==>應用B(服務)

應用A調用的應用的方法B(服務)返回一些JSON信息。但是,如果用戶未登錄到應用程序B,則返回空值。

(在應用程序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,登錄數據將被載入....

請讓我知道,如果需要進一步的信息。 謝謝

+0

Editor prefsEditor = prefsEditor.commit();將這些行更改爲\ prefsEditor.commit(); – Avijit

+0

我已更新我的消息,對不起 – johann

回答

0

通過閱讀您的意見,我可以給你一個快速的解決方案:

更簡單的方法是調用你的服務中的登錄活動之前,簡單地終止您的活動(A)。

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

因此,當您填寫登錄表單並回撥活動A時,它會讀取新的共享首選項!

+0

正如我對Arju所說的,我更新了我的源代碼。對不起! – johann

+0

如果您用B和B重新啓動登錄,A是否正常工作? – iGio90

+0

如果我第一次登錄B應用程序,然後啓動一個應用程序,它運作良好(我的意思是返回JSON)。 – johann

0

由於您需要訪問其他application的共享首選項。

你應該嘗試:: Android: Retrieving shared preferences of other application

+1

Sorrry,我還沒有重新定義編輯器(複製/粘貼錯誤) – johann

+0

好吧,嘗試在該鏈接中的答案由 提供danhnn.uit –

+0

謝謝。自從應用程序B的服務訪問應用程序B的sharedPreferences以來,我不必共享首選項。應用程序A不直接訪問首選項。 – johann

1

經過長期鬥爭,我終於成功地讓我更新的偏好。

當調用getSharedPreferences時,我使用Context.MODE_MULTI_PROCESS標誌。

MODE_MULTI_PROCESS

謝謝。