Launching other application using code in Android

Public on October 8, 2009
Previously we blogged about how to delete application by their package name. Now here is how to open applications using code, note this is not the same as intent-filter.

Say you want to open fuelgauge in Android 1.6, to do this.
final Intent intent = new Intent(Intent.ACTION_MAIN, null);

intent.addCategory(Intent.CATEGORY_LAUNCHER);

final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.fuelgauge.PowerUsageSummary");

intent.setComponent(cn);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity( intent);


Explanation
To open other people's application, you need to make sure that in their manifest file, the author specify the class to have the android.intent.action.MAIN intent-filter added to them.
final Intent intent = new Intent(Intent.ACTION_MAIN, null);

We then add category that this new intent will be launching something
intent.addCategory(Intent.CATEGORY_LAUNCHER);

Then we get identify the application we need to open by using ComponentName, here you specify the package name of the application as first argument and the class we want to open as the second one. You must understand that com.android.settings has a lot of classes that have Main intent-filter under it making the second argument to be the specific class that we need. (this is more than one line)
final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.fuelgauge.PowerUsageSummary");

After we identify the component we want, we set it to our intent
intent.setComponent(cn);

We then tell the intent that open opening this one make it as a new task
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Then finally start our intent
startActivity( intent);

Resources
LauncherProvider.java
IRC #android-dev room

Update History
   Jan 17, 2012 - Visual Update




[Advertising]Faster Thinking - Speed up your brain


Faster Thinking Game



sentiment_satisfied Emoticon