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

ありがとう。

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

@Jimix の正解とは別に、別の回答にコメントされているように、PendingIntent requestCodeを 0 からゼロ以外の値に変更します。一方、以前の Android バージョンには既知のバグがあり、数時間かかってしまいました。そこで提案された解決策は、通知を送信する前にキャンセルすることでうまくいきました:PendingIntent

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

PendingIntent を作成するときは、以下を使用します。

Main.this.getBaseContext()

同じアクティビティに戻りたい場合は、デフォルトのアクティビティ コンテキストを使用する必要があります。ここでもっと読む:

Android - コンテキストを取得するさまざまな方法の違いは何ですか?

于 2011-03-09T15:39:30.620 に答える