Android Intent to start Main activity of application

Abhishek picture Abhishek · Jun 14, 2012 · Viewed 25.6k times · Source

I am trying to start the main activity from inside a BroadcastReceiver. I dont want to supply the activity class name but to use the action and category for android to figure out the main activity.

It doesnt seem to work.

Sending Code:

Intent startIntent = new Intent();

startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startIntent.setAction(Intent.ACTION_MAIN);
startIntent.setPackage(context.getPackageName());
startIntent.addCategory(Intent.CATEGORY_LAUNCHER);        
context.startActivity(startIntent);

I get this error:

Caused bt: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 pkg=com.xyz.abc (has extras) }

Any ideas?

Answer

TienLuong picture TienLuong · Sep 21, 2015

Copy from another topic:

This works since API Level 3 (Android 1.5):

private void startMainActivity(Context context) throws NameNotFoundException {
    PackageManager pm = context.getPackageManager();
    Intent intent = pm.getLaunchIntentForPackage(context.getPackageName());
    context.startActivity(intent);
}