Intent - If Activity Is Running, Bring It to Front, Else Start a New One (From Notification)

Start new activity from notification in existing task

You can't really do this with TaskStackBuilder. It isn't designed for that. It always resets the task to begin with.

I would do the following:

  • Have the Notification start an Activity. Don't use TaskStackBuilder and don't create any artificial back-stack. This Activity will run in the application's current task if the application is currently active, and it will be put on top of the most recent Activity that is open.
  • In onCreate() of this new Activity, check if this Activity is the root of the task using isTaskRoot(). If this Activity is the root of the task, this means that the app was not active prior to launching this Activity. In this case, you can create an artificial back-stack using TaskStackBuilder and launch the thing again the way you want it (this will reset the task).

How to bring an Activity back to the front after i click home button(via notification)

Use this as this will also do the same thing in more elegant manner ( without any side effects )

  final Intent notificationIntent = new Intent(context, YourActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);

or

you can use this too

<activity 
android:name=".YourActivity"
android:launchMode="singleTask"/>

Description of singleTask

The system creates a new task and instantiates the activity at the root of the
new task. However, if an instance of the activity already exists in a separate
task, the system routes the intent to the existing instance through a call to
its onNewIntent() method, rather than creating a new instance. Only one
instance of the activity can exist at a time.

Notification bring app to front without change activity

You don't ever set Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT. That flag is set by Android when it brings the activity to the front. You setting it has no effect.

There's a few ways to do what you want. Check out this answer

Starting app only if its not currently running

Use a "launch Intent" for your app, like this:

PackageManager pm = getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage("your.package.name");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, launchIntent, 0);

Replace "your.package.name" with the name of your package from the Android manifest.

Also, you should remove the special launchMode="singleTask" from your manifest. Standard Android behaviour will do what you want.



Related Topics



Leave a reply



Submit