I want the broadcast receiver to launch my app this way:
If the app is not in the foreground or background, launch it as if it is launched from launcher.
If the app is in the background, bring it to the foreground with the state it was last in.
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!
Since you need behaviour like
1) If the app is not in the foreground or background, launch it as if it is launched from the 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.
Consider:
You don't need to write all that code. You can use a "launch Intent", as follows:
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
Assuming you already know BroadcastReceiver, you just have to do the launching like you usually do on onReceive : Therefore it will look like this
If it is launched before, it will just resume that Activity, if not, it will start a new
It's this simple but unless you know the proper way when you try to get the extra data from your intent you will usually get a java null pointer exception.
Use the
onNewIntent()
method to receive the extra data. If you want to know how comment below.Edit: Try the following. But what I don't understand is the first code which I gave you should work on its own. It has always worked for me. Have you made sure that you have copied the first code I gave you and pasted it without making any changes?
Edit2: If that doesn't work try setting the flag to clearTaskOnLaunch instead of
INTENT.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED