SharedPreferences cross applications

2019-09-17 10:42发布

问题:

I have 2 applications Application 1 (com.mine.app1) in which I have declared a SharedPreference.

SharedPreferences controlinfo = getSharedPreferences("pincode", MODE_WORLD_WRITEABLE | MODE_WORLD_READABLE);
SharedPreferences.Editor editor = controlinfo.edit();

editor.putString("pincode", "dddd");
editor.commit();

I have an application 2 (com.mine.app2) in which I try to read out the SharedPreference from Application 1.

Here I have the following code (under onclick of a button):

Context con = createPackageContext("com.mine.app1", 0);
SharedPreferences interalPref = getSharedPreferences("pincode", MODE_PRIVATE); //shared pref of App 2 (this app)
SharedPreferences externalPref = con.getSharedPreferences("pincode", MODE_PRIVATE); //shared pref of App 1
//note: MODE_PRIVATE doesn't matter

String internalPincode = interalPref.getString("pincode", "none");
String externalPincode = externalPref.getString("pincode", "none");

In this case I get for internalPincode and externalPincode "none".

However when I change the order of getSharedPreference:

Context con = createPackageContext("com.mine.app1", 0);
SharedPreferences externalPref = con.getSharedPreferences("pincode", MODE_PRIVATE); //shared pref of App 1
SharedPreferences interalPref = getSharedPreferences("pincode", MODE_PRIVATE); //shared pref of App 2 (this app)

String internalPincode = interalPref.getString("pincode", "none");
String externalPincode = externalPref.getString("pincode", "none");

I this case I get for both internalPincode and externalPincode “dddd” (which is the value set in Application 1 (com.mine.app1))

I expect that internalPincode will return "none" and externalPincode "dddd" in both case.

Why doesn't it?

回答1:

I have an application 2 (com.mine.app2) in which I try to read out the SharedPreference from Application 1.

This is not a great idea. The user can get rid of Application 1 whenever they wish, at which point Application 2 can no longer get at this data.

Instead, use a synchronization model. Have Application 1 send out a broadcast Intent when preferences change, with an attached signature-level permission so only Application 2 (or any others that you write) can receive it. Application 2 can then update its own local data store (e.g., its own SharedPreferences). Application 2 can do the same, allowing the user to modify its copy of the preference data and sending out the broadcasts to let the other application(s) know. That way, if any one application is removed, the other application(s) do not lose their preference data, yet everything can remain in sync.