Android: always launch top activity when clicked on notification

我们两清 提交于 2019-12-08 09:37:30

问题


EDIT: please note: i completely re-explained my question.

I have application with two Activites: A and B. Activity A is MAIN. So, application starts, and A appears on the screen. User press the button on it, and new Activity B appears on the screen.

So, there's now 2 activities in my "back stack": A and B.

Now I press "Home" key, and then click on my app's icon on launcher: Activity B appears on the screen (not A), as far as it is top activity in my task.

Now question: how can i make Intent to similarly open the currently top Activity of my task?

I need it to use in Notification: when user clicks on my Notification, top Activity of this task should appear on the screen, not a specified one.

I tried many Intent flags, such as SINGLE_TOP and others, but i still can't get what i need.

Does anyone know the solution?


回答1:


Well, after spending several hours some days, i found the solution:

Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

That's the way which launcher starts applications, and it works nice for notification Intent too.




回答2:


I used like this.

private void notifyUser(Context context) {

    notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    CharSequence text = "Test Notification";
    Notification notification = new Notification(R.drawable.icon, text,
            System.currentTimeMillis());

    Intent resultIntent = new Intent(context, StartActivity.class);
    resultIntent.setAction(Intent.ACTION_MAIN);
    resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(GeneralSettingsActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);

    notification.flags = Notification.FLAG_AUTO_CANCEL;
    notification.setLatestEventInfo(context, "Title", text,
            resultPendingIntent);
    notificationManager.notify(AUTOSYNC_COMPLETED_NOTIFICATION,
            notification);

}



回答3:


you can use android:launchMode="singleInstance". May this will working.



来源:https://stackoverflow.com/questions/8655388/android-always-launch-top-activity-when-clicked-on-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!