W. VM
W. VM

Reputation: 23

SharedPreferences between apps doesn't update after resuming

I'm trying to share data (just 1 simple Long) between two apps. App 2 writes data to his own SharedPreferences, which are then accessed by app 1. Since app 2 gets launched from within app 1, app 1 only gets paused. Now app 1 reads the data just fine, but doesn't update the data, though it does read from the sharedpreferences. Only if app 1 gets destroyed and recreated, it gets the updated value. How can I make it update immediately without destroying? This gets called in the onResume of app 1.

Context con = createPackageContext("com.app2.android", 0);
SharedPreferences pref = con.getSharedPreferences(
                    "MyPreferences", Context.MODE_PRIVATE);
data = pref.getLong("data", 0);

Upvotes: 2

Views: 126

Answers (1)

gaurav jain
gaurav jain

Reputation: 3234

While reading preferences from app 1, use Context.MODE_MULTI_PROCESS. This would force it to read the preference every time from the disk, and you'd get the updated value. Something like this :

SharedPreferences prefs = mOtherAppContext.getSharedPreferences("profilePref", Context.MODE_MULTI_PROCESS);

More info on this link : http://developer.android.com/reference/android/content/Context.html#MODE_MULTI_PROCESS

Though I know, it's deprecated but I didn't find any other way of doing it . Any better solution would be helpful but for the time being, this would solve your problem.

Upvotes: 1

Related Questions