Reuse current app instance when clicking on Notification

1.1k Views Asked by At

Right now I'm using a PendingIntent to launch my desired Activity from the Notification. But I want to know if it's possible to reuse the current app instance.

For example:

  • Launch app, the Launcher Activity is called HomeActivity
  • Navigate to SecondActivity
  • Press the home button
  • Click on the notification from the app and resume SecondActivity

But if the user didn't navigate to the SecondActivity i want to open the HomeActivity when I click on the Notification. I would be glad for any help regarding this problem :)

1

There are 1 best solutions below

10
On

But I want to know if it's possible to reuse the current app instance.

Yes, you can reuse if the app is in background. In PendingIntent you will pass an Intent, so in that Intent you should set a flag like intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); so if the app is in background it will just bring activity to front.

According to android docs :

FLAG_ACTIVITY_NEW_TASK

Added in API level 1 int FLAG_ACTIVITY_NEW_TASK If set, this activity will become the start of a new task on this history stack. A task (from the activity that started it to the next task activity) defines an atomic group of activities that the user can move to. Tasks can be moved to the foreground and background; all of the activities inside of a particular task always remain in the same order. See Tasks and Back Stack for more information about tasks.

This flag is generally used by activities that want to present a "launcher" style behavior: they give the user a list of separate things that can be done, which otherwise run completely independently of the activity launching them.

When using this flag, if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in. See FLAG_ACTIVITY_MULTIPLE_TASK for a flag to disable this behavior.

This flag can not be used when the caller is requesting a result from the activity being launched.

Check the docs here

But if the user didn't navigate to the SecondActivity i want to open the HomeActivity.

Why do you launch HomeActivity if your notification intent class you are creating have SecondActivity as the launcher. It will create a new SecondActivity and launches it if it is not in background.

EDIT:
If you want to relaunch app where you left off try like this :

final Intent resumeIntent = new Intent(context, YourLauncher.class);
resumeIntent.setAction("android.intent.action.MAIN"); 
resumeIntent.addCategory("android.intent.category.LAUNCHER"‌​);
final PendingIntent resumePendingIntent = PendingIntent.getActivity(context, 0, resumeIntent, 0);

Here YourLauncher.class is the launcher class name.