【问题标题】:Clearing the old activities so they don't show up on new activity click清除旧活动,使其不会出现在新活动点击
【发布时间】:2013-11-25 21:53:19
【问题描述】:

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

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

【问题讨论】:

  • 你可以在离开时使用finish()一个活动,这样会更容易

标签: android android-intent android-activity notifications


【解决方案1】:

这行不通。你写过:

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

这说的是“如果任务堆栈中已经存在活动Dialog,则在启动Dialog活动之前清除(完成)堆栈中位于该活动之上的所有活动。否则(如果没有实例Dialog 已经在堆栈中)只需启动 Dialog 活动”。所以你看到的是你的Dialog 活动被放置在已经在任务堆栈中的其他活动之上。

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

像这样创建通知:

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

在这种情况下,MyRootActivity 必须是任务的根活动(即:清单中包含 ACTION=MAIN 和 CATEGORY=LAUNCHER 的活动)。

onCreate()MyRootActivity 中这样做:

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...

希望这很清楚。

【讨论】:

  • 非常感谢您。并解释为什么它对我不起作用。
  • 再问一个问题,我将如何使这项工作成为一项服务。因为在我的服务类中它不识别方法 finish();或 getIntent(); @大卫瓦瑟
  • 抱歉,不太明白这个问题。您不能在服务中显示对话框。你想做什么?
  • 这不是一个实际的对话框,它是一个称为对话框的活动,因为它复制了一个。因为它没有标题栏,它就像一个活动的四分之一。该代码适用于正常活动,但不适用于服务。
  • 对不起,我还是不明白。如果您可以从您的服务中发布更多代码并解释什么不起作用,我将很乐意提供帮助
猜你喜欢
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 2023-01-04
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
相关资源
最近更新 更多