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());

  ResolveInfo ri = pm.resolveActivity(intent,

  if (ri != null) {
   Intent i = new Intent();

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

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

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


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