22

我正在开发一个向用户显示通知的应用程序。通知的目的是让用户在用户处于另一个活动时更容易返回活动。我在我的应用程序中使用此代码来创建和显示通知。

                    notification = new Notification(R.drawable.icon,
                            "Notify",
                            System.currentTimeMillis());
                    notification.setLatestEventInfo(this, "App name",
                            "App message",
                            PendingIntent.getActivity(
                                    this, 0,
                                    new Intent(this, Main.class),
                                    PendingIntent.FLAG_CANCEL_CURRENT));
                    notification.flags |= Notification.FLAG_ONGOING_EVENT;
                    nManager.notify(0, notification);

但是当用户点击通知时,会启动同一活动的新实例,而不是用户之前使用的那个。

我认为这与 PendingIntent 有关,但我找不到如何使该 Intent 恢复先前暂停的活动实例而不是创建新实例。

谢谢。

4

5 回答 5

22

我发现了如何做到这一点。我添加了以下代码:

notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

现在我的代码如下所示:

    notification = new Notification(R.drawable.icon,
            "Notify", System.currentTimeMillis());
    notification.setLatestEventInfo(this, "App name",
            "App message", PendingIntent.getActivity(this,
                    0, new Intent(this, Main.class)
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                                    | Intent.FLAG_ACTIVITY_SINGLE_TOP),
                    PendingIntent.FLAG_CANCEL_CURRENT));
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
于 2011-03-09T17:01:18.183 回答
9

这对我有帮助android:launchMode="singleInstance"

<activity
        android:name="com.mosis.automatskidnevnik.MainActivity"
        android:launchMode="singleInstance"
        android:label="@string/app_name" >
        ...
于 2014-07-05T17:37:48.743 回答
1

我通过设置解决了同样的问题

android:launchMode="singleTask"
于 2014-11-26T09:20:50.303 回答
0

创建 PendingIntent 时,您使用:

Main.this.getBaseContext()

如果要返回相同的活动,则应使用默认活动上下文。在这里阅读更多:

Android - 获取上下文的各种方法有什么区别?

于 2011-03-09T15:39:30.620 回答
0

除了@Jimix 的正确答案之外,我会将根据另一个答案PendingIntent requestCode的评论从 0更改为非零值。另一方面,以前的 Android 版本有一个已知的错误,让我花了几个小时的时间。那里提出的解决方案对我取消发送通知之前的效果很好:PendingIntent

if (Build.VERSION.SDK_INT == 19) {
   getNotificationPendingIntent().cancel();
}
于 2015-04-08T07:01:30.097 回答