意图恢复以前暂停的活动(从通知中调用)

Jim*_*mix 21 notifications android android-activity android-pendingintent

我正在开发一个向用户显示通知的应用程序.通知的目的是使用户在另一个活动中轻松返回活动.我在我的应用程序中使用此代码来创建和显示通知.

                    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);
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢.

Jim*_*mix 22

我发现了怎么做.我添加了以下代码:

notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
Run Code Online (Sandbox Code Playgroud)

现在我的代码看起来像这样:

    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;
Run Code Online (Sandbox Code Playgroud)


小智 9

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

<activity
        android:name="com.mosis.automatskidnevnik.MainActivity"
        android:launchMode="singleInstance"
        android:label="@string/app_name" >
        ...
Run Code Online (Sandbox Code Playgroud)


Yos*_*ssi 0

创建 PendingIntent 时,您可以使用:

Main.this.getBaseContext()

如果您想返回相同的活动,您应该使用默认的活动上下文。在这里阅读更多内容:

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