web-dev-qa-db-ja.com

以前に一時停止したアクティビティを再開する意図(通知から呼び出されます)

ユーザーに通知を表示するアプリを開発しています。通知の目的は、ユーザーが別のアクティビティに参加しているときに、ユーザーがアクティビティに簡単に戻れるようにすることです。アプリでこのコードを使用して、通知を作成して表示しています。

                    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と関係があると思いますが、新しいインスタンスを作成する代わりに、以前に一時停止したアクティビティのインスタンスを再開するようにそのインテントを作成する方法が見つかりません。

ありがとう。

21
Jimix

私はそれを行う方法を見つけました。次のコードを追加しました。

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;
22
Jimix

これは私にとって役立ちますAndroid:launchMode="singleInstance"

<activity
        Android:name="com.mosis.automatskidnevnik.MainActivity"
        Android:launchMode="singleInstance"
        Android:label="@string/app_name" >
        ...
9
Zeljko Ivanovic

設定して同じ問題を解決しました

Android:launchMode="singleTask"
1

@Jimixの正解とは別に、別の answer にコメントされているように、PendingIntentrequestCodeを0からnon zero値に変更します。 =。一方、以前のAndroidバージョンでは2、3時間かかった 既知のバグ があります。そこで提案されたソリューションは、PendingIntentをキャンセルするためにうまく機能しました。通知を送信する前:

if (Build.VERSION.SDK_INT == 19) {
   getNotificationPendingIntent().cancel();
}
0
GoRoS

保留中のインテントを作成するときは、次を使用します。

Main.this.getBaseContext()

同じアクティビティに戻りたい場合は、デフォルトのアクティビティコンテキストを使用する必要があります。詳細はこちら:

Android-コンテキストを取得するためのさまざまなメソッドの違いは何ですか?

0
Yossi