Android Intent to start Main activity of application

13

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?

android
android-intent
alarmmanager
asked on Stack Overflow Jun 14, 2012 by Abhishek • edited Jun 23, 2015 by Armand

4 Answers

16

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);
}
answered on Stack Overflow Sep 21, 2015 by TienLuong
8

this is not the right way to startActivity.
try this code instead:

Intent startIntent = new Intent(context, MainActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        
context.startActivity(startIntent);
answered on Stack Overflow Jun 14, 2012 by Tal Kanel
1

Even I had been trying to launch the MainActivity via a library Activity.

And this worked for me:

Intent startIntent = new Intent();
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startIntent.setPackage(getApplicationContext().getPackageName());
getApplicationContext().startActivity(startIntent);

Make sure you add the activity in your library's manifest!

answered on Stack Overflow Jun 4, 2014 by Arnab Saha • edited Jun 11, 2014 by Arnab Saha
0

Even though it is too late. Might be useful for somone in the future. This helped me.

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
answered on Stack Overflow Aug 20, 2019 by cantona_7

User contributions licensed under CC BY-SA 3.0