08 agosto 2011

Run Activity with Intent without knowing the class

I was having a problem this evening where I had to call an activity that I didn't want to know the class name. My problem was exactly this: I have several activities, each with a String id. And in activity A I call goToScreen("b"); to load activity B.

To make this work one need to do this:

public void goToScreen(String id) {
  PackageManager pm = androidContext.getPackageManager();
  Intent intent = new Intent("com.myproject.screen."
    + id.toUpperCase());
  intent.addCategory(Intent.CATEGORY_DEFAULT);

  ResolveInfo ri = pm.resolveActivity(intent,
    PackageManager.MATCH_DEFAULT_ONLY);

  if (ri != null) {
   Intent i = new Intent();
   i.setClassName(ri.activityInfo.applicationInfo.packageName,
     ri.activityInfo.name);
   androidContext.startActivity(i);
  }
 }

This code will call an activity mapped on AndroidManifest.xml like this:

<activity android:label="@string/app_name" android:name=".AvisoActivity">
   <intent-filter>
      <action android:name="com.myproject.screen.AVISO" />
      <category android:name="android.intent.category.DEFAULT" />
   </intent-filter>
</activity>


The DEFAULT category is not optional, as one may think. If you don't put both references (Java and XML) of the category, this code won't work. I don't know if it's a bug at Android or just a non-documented feature (which is a bug to me, anyway).

Also, don't forget to call resolveActivity with MATCH_DEFAULT_ONLY.

This is all for tonight and this blog post is more like of a reminder to myself. =)
Postar um comentário
Contato

Email:bruno.borges(at)gmail.com

LinkedIn: www.linkedin.com/in/brunocborges
Twitter: www.twitter.com/brunoborges
Comprei e Não Vou
Rio de Janeiro, RJ Brasil
Oracle
São Paulo, SP Brasil