android - 清除旧 Activity ,这样它们就不会出现在新 Activity 中点击

标签 android android-intent android-activity notifications

所以我在状态栏中有一个通知,当用户单击该通知时,它会弹出一个没有标题的 Activity ,以复制一个对话框。但我有一个问题。如果我打开应用程序,只需单击主页按钮,然后单击状态栏中的通知。它会显示应用程序的主要 Activity ,通知 Activity 堆叠在顶部。我想要做的是,当我点击通知时,它会清除所有底部 Activity ,这样就不会发生。这是我用来启动通知 Activity 的代码

// Send Notification
Intent intent1 = new Intent(this, Dialog.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_quick_tweet_icon)
.setContentTitle("Dialog")
.setContentText("Touch for more options")
.setWhen(System.currentTimeMillis())
.setContentIntent(pIntent)
.setAutoCancel(false).setOngoing(true);
NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = builder.getNotification();
nm.notify(1, notif);

最佳答案

这行不通。你写过:

Intent intent1 = new Intent(this, Dialog.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

这意味着“如果 Activity Dialog 已经存在于任务堆栈中,则在启动 Dialog 之前清除(完成)堆栈中位于该 Activity 顶部的所有 Activity > Activity 。否则(如果堆栈中没有 Dialog 实例)只需启动 Dialog Activity ”。因此,您看到的是您的 Dialog Activity 位于任务堆栈中已有的其他 Activity 之上。

如果您希望此通知从任务堆栈中删除所有 Activity ,然后启动您的 Dialog Activity ,我建议您执行以下操作:

像这样创建通知:

Intent intent1 = new Intent(this, MyRootActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent1.putExtra("startDialog", true);

在这种情况下,MyRootActivity 必须是任务的根 Activity (即:在 list 中具有 ACTION=MAIN 和 CATEGORY=LAUNCHER 的 Activity )。

MyRootActivityonCreate() 中执行此操作:

super.onCreate(...);
if (getIntent().hasExtra("startDialog")) {
    // User has selected the notification, so we show the Dialog activity
    Intent intent = new Intent(this, Dialog.class);
    startActivity(intent);
    finish(); // finish this activity
    return; // Return here so we don't execute the rest of onCreate()
}
... here is the rest of your onCreate() method...

希望这是清楚的。

关于android - 清除旧 Activity ,这样它们就不会出现在新 Activity 中点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20204133/

相关文章:

java - 扩展 Listadapter 时出现运行时错误

android - 从 Activity 向服务发送 "share intent"(ACTION_SEND)

android - Intent 并从字符串开始 Activity

android - 防止我的 Android 应用程序的多个实例由单个 Activity 组成

Android - 进程终止后恢复 Activity 堆栈?

java - 以编程方式更改自定义按钮形状的颜色

java - MVP - View 中的数据不显示

android - 如何将整个应用程序的可下载字体设置为默认字体?

java - 如何将 JSON 值发送到另一个 Activity(Android)

android - 像 any.do 一样的弹出窗口