Search code examples
androidandroid-intentandroid-activitybroadcastreceiver

Android - launch app from broadcast receiver


I want the broadcast receiver to launch my app this way:

  1. If the app is not in the foreground or background, launch it as if it is launched from launcher.

  2. If the app is in the background, bring it to the foreground with the state it was last in.

  3. If the app is in the foreground, do nothing.

Here is my code:

@Override
public void onReceive(Context context, Intent intent) {
        Intent launch_intent = new Intent("android.intent.action.MAIN");
        launch_intent.setComponent(new ComponentName("com.example.helloworld","com.example.helloworld.MainActivity"));
        launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        launch_intent.addCategory(Intent.CATEGORY_LAUNCHER);
        launch_intent.putExtra("some_data", "value");
        context.startActivity(launch_intent);
}

MainActivity is my root activity. Like I said, if the app is already running, I just want it brought to the front without changing its state. If there is some activity on top of MainActivity, leave it as it is.

Most of the time the above code worked fine, but sometimes I noticed that the app was restarted (or the state was reset --- the root was back on top) when it was brought from the background.

What code should I be using? Any help is appreciated!


Solution

  • You don't need to write all that code. You can use a "launch Intent", as follows:

    PackageManager pm = context.getPackageManager();
    Intent launchIntent = pm.getLaunchIntentForPackage("com.example.helloworld");
    launchIntent.putExtra("some_data", "value");
    context.startActivity(launchIntent);
    

    However, your code should also work.

    If you say this works most of the time, you might be seeing a nasty old Android bug in those cases. This occurs when you launch your app for the first time either directly from the installer, or via an IDE (Eclipse, Android Studio, etc.). You should always launch your app for the first time directly from the HOME screen or list of installed apps. For more information about this frustrating Android bug see https://stackoverflow.com/a/16447508/769265