Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedUserId access SharedPreferences

I got two apps, with these package names:

  • com.blah.a
  • com.blah.b

They got the sharedUserId "com.blah.shared". At /data/data in my device they both got a folder with there data, which contains the shared_prefs folder and the default SharedPreferences files named:

  • com.blah.a_preferences.xml
  • com.blah.b_preferences.xml

I know that two apps with the same sharedUserId can access each others files. How can I read app a's SharedPreferences from app b?

I found one solution, but it is neither working well (if app a updates a preference, app b still reads the old value) nor good code (can throw exception).

try {
    Context c = context.createPackageContext("com.blah.a", 
        Context.CONTEXT_IGNORE_SECURITY))

    aPrefs = PreferenceManager.getDefaultSharedPreferences(c);
} catch (NameNotFoundException e) {
}

Thanks for your help!

like image 240
Gabriel Ittner Avatar asked Mar 16 '26 04:03

Gabriel Ittner


1 Answers

Generally, you shouldn't need to do this, and sharedUserId is a bad idea for production apps. In any case, this is the code to do it, but you don't need to specify IGNORE_SECURITY. If your apps have the same UID, they should be able to read each other's (private) files. As for the exception, an exception will only be thrown if the package doesn't exists. You could check if it does, and only execute the code if it exists (i.e., the other app is installed). There is probably some caching, so you should load the prefs each time you need them.

like image 179
Nikolay Elenkov Avatar answered Mar 17 '26 18:03

Nikolay Elenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!