【问题标题】:Determine if Activity is called by a Notification确定 Activity 是否被 Notification 调用
【发布时间】:2013-01-02 12:31:21
【问题描述】:

我正在使用带有各种标签Activity。从应用程序的不同部分创建通知以告诉用户某些事情发生了变化。当用户点击 Notification 时,我现在设法调用 Activity。但是我如何确定 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触发Activity时是否有一些方法被调用?

考虑在 Main Activity 中定义类似的东西:

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

【问题讨论】:

    标签: android notifications android-pendingintent


    【解决方案1】:

    从通知中传递一个布尔值并在活动的 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");
    }
    

    【讨论】:

      【解决方案2】:

      你可以在你的通知

      中试试这个
      Intent intent=new Intent();
      intent.setAction("Activity1");
      

      Activity 中覆盖 onNewIntent() 方法并获取操作,以便您确定是否调用了 Activity。

      【讨论】:

      • 我试过了,但是onNewIntent方法在任何时候都没有触发。
      • 好的,然后尝试在活动的 onCreate() 中获取意图。
      【解决方案3】:

      比使用 @ricintech 指定的意图的保留操作字段更好,您可以在待处理的意图中使用额外的参数,并在您的 onCreate 方法和活动中的 onNewIntent 方法中检测它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多