My Android App consists of a single Activity containing two fragments accessed with tabs (I'm using a ViewPager).
Inside Fragment #2, a notification is created from a button. This button starts a background task that needs to continue if the user sends the app to background with the home button, for example.
I want the user to be able to bring back the application to the front when clicking the notification, exactly as if the app icon was used. Here is my code :
Notification.Builder mBuilder =
new Notification.Builder(getActivity())
.setSmallIcon(R.drawable.ic_stat_av_play)
.setContentTitle("MyApp")
.setContentText("A background task is running");
Intent notificationIntent = new Intent(getActivity(), MainActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent notificationPendingIntent = PendingIntent.getActivity(
getActivity(), 0, notificationIntent, 0);
mBuilder.setContentIntent(notificationPendingIntent);
mNotificationManager = (NotificationManager) getActivity().getSystemService(
Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
Unfortunately, clicking the notification closes the currently running application and starts it again.
As you can see, I have tried the solution proposed here: Resume application and stack from notification, but it does not work. Many similar questions also suggest to use one or more of these flags:
FLAG_ACTIVITY_CLEAR_TOP
FLAG_ACTIVITY_SINGLE_TOP
FLAG_ACTIVITY_NEW_TASK
FLAG_ACTIVITY_REORDER_TO_FRONT
I found out that none of these has any effect on my notification behavior. Is there something I am missing to make this work as intended?
Edit:
Maybe this will help you to help me. The problem really seems to come from the app structure.
If I replace this line :
Intent notificationIntent = new Intent(getActivity(), MainActivity.class);
by this one :
Intent notificationIntent = new Intent(getActivity(), Fragment2.class);
The notification behavior will be correct if it is clicked while the app is still in the foreground (ie the notification drawer will simply close itself) However, if I return to the home screen with the home button, and then click the notification, nothing happens.
If I use the first intent definition (with MainActivity.class), none of the flags has any effect on the intent. This also applies to the launchMode defined in the manifest.
Edit 2
Solution added. I'm not too sure about why it is working, so any additional input would be appreciated!