I've read some answers here, I think I have what I need in order to achieve my result, but I need some help.
My app launches an notification on specific conditions, and I need my app to behave as follow:
if there is an instance of my main activity running in background I need to make it to the foreground (I found this on the site: intent.setFlags(FLAG_ACTIVITY_REORDER_TO_FRONT);
, so I think this point is solved;
if there isn't any activity of the app running in background I need to start the app from the beginning (and this can be achieved starting the launcher activity of the app.);
My question is: how can I make the app search for any istance of itself running in background? Because the activity that I need to reorder to front with the Intent flag is different from the launcher activity.
The notification is handled by a service that check periodically some infos from the internet.
Thanks for the help.
What you need is just a simple Activity that decides what to do. Here is an example:
public class NotificationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check if the app was already running
if (isTaskRoot()) {
// App wasn't running, so start the app from the beginning
Intent startIntent = new Intent(this, MyStartingActivity.class);
startActivity(startIntent);
} else {
// App was already running, bring MainActivity to the top
Intent reorderIntent = new Intent(this, MainActivity.class);
reorderIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(reorderIntent);
}
// We are done now so just finish
finish();
}
}
Set up your notification to start this activity. Make sure that in the manifest the task affinity of this activity is the same as the task affinity of the other activities in your application (by default it is, if you haven't explicitly set android:taskAffinity).