Android:点击通知时始终启动热门活动

时间:2011-12-28 11:35:56

标签: android android-activity notifications

编辑:请注意:我完全重新解释了我的问题。

我有两个Activites申请: A B Activity A MAIN。因此,应用程序启动,并在屏幕上显示 A 。用户按下按钮,屏幕上会出现新的Activity B

所以,现在我的“后台”中有两项活动: A B

现在我按“主页”键,然后点击启动器上我的应用程序图标:Activity B 出现在屏幕上(不是A ),至于它是我任务中的顶级活动。

现在提问:如何让Intent同样打开我当前最高Activity 的任务?

我需要在Notification中使用它:当用户点击我的Notification时,此任务的顶部Activity应显示在屏幕上,而不是指定的任务。

我尝试了许多Intent标志,例如SINGLE_TOP和其他标志,但我仍然无法得到我需要的东西。

有谁知道解决方案?

3 个答案:

答案 0 :(得分:9)

好吧,几天后花了几个小时,我找到了解决方案:

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);

这就是启动器启动应用程序的方式,它也适用于通知Intent。

答案 1 :(得分:1)

我这样用过。

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);

}

答案 2 :(得分:0)

你可以使用android:launchMode =“singleInstance”。 愿这可行。