Chris Risner . Com
Posted on: 8/12/2012 2:12:00 AM by Chris
A while back, I wrote about using shared preferences in Android. Recently, one person commented on that post saying that they weren’t able to access the shared preferences of one application from another using the MODE_WORLD_READABLE or MODE_WORLD_WRITEABLE flags and would like to see some sample code. I decided to put something together really quick to demonstrate this in action.
What are Shared Preferences
Just to recap things, shared preferences are a way to store simple key value pairs for an application. These bits of data are persisted across starting and stopping the app. The user does have the ability to remove them by clearing the app’s data (available in the settings) but under normal circumstances, if you commit a change to the shared preferences when the app is running, it will be there the next time the app loads. For an example of something you might store in shared preferences, let’s consider if when your app runs, it first presents a login dialog (username and password) to the user. You might want to store the user’s username in shared prefs so that the next time the app runs, their name is already filled out and they only need to enter the password.
Writing a Preference so it’s Available in Other Apps
Writing e preference so it’s readable by other apps is actually very simple. In fact, the only difference between writing “private” shared prefs and ones readable by other apps is the mode you use when getting a reference to the shared prefs.
Here, we’re using Context.MODE_WORLD_READABLE for the mode when fetching the shared prefs. This set’s the file that is generated to store these preferences to be readable by any application. With that done, we’re just putting a String extra in preferences just like any other preference we might store.
Reading a Preference from another App
This is where things get a little more tricky. Prior to getting a reference to shared prefs, we need to generate a context which points to the app that generated the shared preference. So, let’s pretend that the app above that saved the shared preference had the package name “com.cr.sharedprefexampleone”, we would need a reference to that app’s context.
Here we get a context for the first app and use the Context.MODE_WORLD_WRITEABLE mode for the context. Then, we use that context to get the reference to shared preferences with the Context.MODE_WORLD_READABLE mode. With that done, we can extract our String extra just like if it had been generated by the second app.
While a powerful ability if you’re releasing several apps, this may not be the best way to share data and isn’t without risk. Doing this means that any app is able to read your shared preferences. If this is how you’re going to share data, you may want to look into the sharedUserId attribute in your AppManifest. You can download sample code with two apps that perform the above here.