7

さまざまなタブを持つアクティビティを使用しています。アプリケーションの別の部分から、何かが変更されたことをユーザーに知らせる通知が作成されます。ユーザーがNotificationをクリックすると、 Activityを呼び出すことができました。しかし、アクティビティが実行時に「通常の」方法で作成されたか、通知をクリックして作成されたかをどのように判断できますか?

(クリックされた通知によっては、メインのタブを表示する代わりに別のタブに転送したい。)

Intent intent = new Intent(ctx, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, 0);

        // TODO: Replace with .Build() for api >= 16
        Notification noti = new Notification.Builder(ctx)
                .setContentTitle("Notification"
                .setContentText(this.getName())
                .setSmallIcon(R.drawable.icon)
                .setContentIntent(pendingIntent)
                .setDefaults(
                        Notification.DEFAULT_SOUND
                                | Notification.DEFAULT_LIGHTS)
                .setAutoCancel(true)
                .getNotification();

        NotificationManager notificationManager = (NotificationManager) ctx
                .getSystemService(Context.NOTIFICATION_SERVICE);

        // Hide the notification after its selected
        notificationManager.notify(this.getId(), noti); 

これにより、MainActivity が正常に呼び出されます。しかし、アクティビティがによってトリガーされたときに呼び出されるメソッドはありpendingIntentますか?

Main Activityで次のようなものを定義しようと考えました:

onTriggeredByNotification(Notification noti){
     //determinte tab, depending on Notification.
}
4

3 に答える 3

20

通知からブール値を渡し、アクティビティの onCreate メソッドで同じかどうかを確認します。

 Intent intent = new Intent(ctx, MainActivity.class);
 intent.putExtra("fromNotification", true);

...

if (getIntent().getExtras() != null) {
  Bundle b = getIntent().getExtras();
  boolean cameFromNotification = b.getBoolean("fromNotification");
}
于 2013-01-02T12:45:00.290 に答える
1

通知でこれを試すことができます

Intent intent=new Intent();
intent.setAction("Activity1");

アクティビティオーバーライドメソッドと get アクションで、onNewIntent()アクティビティが呼び出されたかどうかを判断できます。

于 2013-01-02T12:37:08.493 に答える
1

@ricintech で指定されたインテントの予約済みアクション フィールドを使用するよりも、保留中のインテントで追加のパラメーターを使用して、アクティビティ内のonCreateメソッドとメソッドでそれを検出できます。onNewIntent

于 2013-01-02T12:39:35.530 に答える