Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting Android Launch Intents?

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?

like image 702
Matt Gibson Avatar asked Mar 30 '26 23:03

Matt Gibson


1 Answers

Well, you can call toUri() on the Intent to have it converted into a Uri, which you can then turn into a String via the standard toString(). To reverse the process, parse the String into an Intent using Intent.parseUri().

However, you will need to add in sufficient protection to deal with various possibilities, such as:

  • the user removed the app
  • the user upgraded the app, and the app no longer supports the Intent you saved

Also, please be careful where you stick that probe (text). :-)

like image 169
CommonsWare Avatar answered Apr 02 '26 14:04

CommonsWare