I’m creating a custom Preference to remember which activity a user wants to run from a list of possibilities. (Effectively implementing the “always launch this activity when you see this kind of intent” of the Chooser, but specifically remembering the result for my particular application, rather than system-wide.)
I get a list of possible Activities like this:
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_TEXT, "Probe text");
PackageManager manager = getContext().getPackageManager();
List<ResolveInfo> infoList = manager.queryIntentActivities(myIntent,PackageManager.MATCH_DEFAULT_ONLY);
…resulting in a list of ResolveInfos.
My question is, once my user has chosen one of these, what’s the best way to persist this as a preference? That is, what do I write into my SharedPreferences (in a single item, if possible), and how, on the next run of my app, do I read that and fire off the corresponding Intent?
Well, you can call
toUri()on theIntentto have it converted into aUri, which you can then turn into aStringvia the standardtoString(). To reverse the process, parse theStringinto anIntentusingIntent.parseUri().However, you will need to add in sufficient protection to deal with various possibilities, such as:
Intentyou savedAlso, please be careful where you stick that probe (text). 🙂