Question

In my app, i created a custom notification that contain a button that show recent apps(instead of home button long press)

when user open main activity and press home button to go to home screen then drag the notification drawer and click on the button:

Desired result is that the recent apps are shown and the main activity is one of the recent apps.

Actual result is that the recent apps are shown but the main activity is not in them and the main activity resumes.

My code to start "RecentApps (is a dummy class that show recent apps)" class with pending intent

    Intent recentAppIntent = new Intent(getBaseContext(), RecentApps.class);
    PendingIntent pendingrecentAppIntent = PendingIntent.getActivity(getBaseContext(), 1, recentAppIntent, 0);
    notificationView.setOnClickPendingIntent(R.id.recentAppButt, pendingrecentAppIntent);

I think that the problem is getBaseContext, so when the main activity is alive and not finished the recent apps are shown but with context is the main activity.

I tried getApplication and getApplicationContext but not working.

I also tried to use flags for "recentAppIntent" but it is not working, It is a half solution to use

recentAppIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

but it not what i need.

So, my question is "How to finish the main activity in which the pending intent starts".

Thanks in advance, Mostafa

Was it helpful?

Solution

You need to ensure that your MainActivity and your RecentApps don't belong to the same task. The "Recent apps" doesn't actually show recent apps. It shows recent tasks.

To make sure that your RecentApps isn't in the same task as your MainActivity, you can add the following to the <activity> definition in the manifest for RecentApps:

aandroid:taskAffinity=""

Also, when creating the notification, add FLAG_ACTIVITY_NEW_TASK to the Intent, like this:

Intent recentAppIntent = new Intent(getBaseContext(), RecentApps.class);
recentAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingrecentAppIntent = PendingIntent.getActivity(getBaseContext(), 1, recentAppIntent, 0);
notificationView.setOnClickPendingIntent(R.id.recentAppButt, pendingrecentAppIntent);

OTHER TIPS

I think FLAG_ACTIVITY_CLEAR_TOP will help as a flag.

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Explanation for Intent flags are available here: link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top