问题
I have a location service running and I want to alert the user if my main activity hasn't been active for several minutes, so from the service I am showing a notification with the code below (based on the example here), using a flag FLAG_ACTIVITY_REORDER_TO_FRONT
instead of FLAG_ACTIVITY_NEW_TASK
.
But it always starts a new copy of the activity, rather than carrying on where the existing one left off.
Intent resultIntent = new Intent(ctx, MainActivity.class);
resultIntent.setAction(Intent.ACTION_VIEW );
resultIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
// Create the TaskStackBuilder and add the intent, which inflates the back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(ctx);
stackBuilder.addNextIntentWithParentStack(resultIntent);
// Get the PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(ctx);
notificationManager.notify(NOTIFICATION_ID , builder.build());
Just to clarify, all I want to happen when the notification is clicked, is the same as what would happen if the standard task-switch control is used to navigate back to my activity when a different app is in use.
The question here sounds the same as my situation, but all the answers explain in length about saving and restoring states. Why is this necessary, when I can switch between apps in the normal way without saving states? I guess I'm misunderstanding something pretty basic here.
[Edit]
As mentioned in a comment below, I have now found an answer for Android 8. But my Android 10 device still restarts the app rather than just switching to it. In logcat I see the following at the time of the attempted switch:
2021-01-22 22:48:57.585 26173-26173/? I/n.wandrerhelpe: Late-enabling -Xcheck:jni
2021-01-22 22:48:57.619 26173-26173/? E/n.wandrerhelpe: Unknown bits set in runtime_flags: 0x8000
then there is a 2-second gap before the log shows the app starting from the beginning.
[Later edit] After comments and more tests, my intent for the notification looks like this:
Intent resultIntent = new Intent(ctx, NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, resultIntent, 0);
with the simple NotificationActivity as suggested by @David Wasser:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Now finish, which will drop the user in to the activity that was at the top
// of the task stack
finish();
}
All working well in Android 8 but not 10
来源:https://stackoverflow.com/questions/65837228/how-to-switch-to-an-existing-activity-rather-than-start-a-new-one