【问题标题】:Generic Listener when a notification is clicked or dismissed in Android在 Android 中单击或关闭通知时的通用侦听器
【发布时间】:2017-03-01 09:00:28
【问题描述】:

我想知道 NotificationListenerService 是否有办法知道通知是否已被单击或已被解除。我可以看到 NotificationListenerService 中的内部类 NotificationListenerWrapper 有一个 onNotificationClick() 方法,但由于 NotificationListenerWrapper 被 @hide 注释隐藏,我无法使用它。

我的问题是我可以编写一个监听器,它基本上可以跟踪通知是否已被点击或关闭。

基本上,我想跟踪我的应用程序的通知是否被关闭,或者在每个通知中没有任何侵入性代码的情况下单击它们。

附: NotificationListenerService 只提供 onNotificationPosted() 和 onNotificationRemoved(),但我的要求是知道通知是否被点击或移除。

谢谢

【问题讨论】:

  • 您会知道您的通知是否通过待处理意图被点击?
  • 所有通知..这是目标
  • 您对设置内容意图不满意吗?

标签: android android-notifications


【解决方案1】:

当您创建和显示通知时,您提供了一个PendingIntent 用于单击它(使用.setContentIntent)。您还可以定义一个PendingIntent 用于何时被解雇(使用.setDeleteIntent(PendingIntent)

如果您希望能够跟踪您的通知,您需要传递一个 PendingIntent(如 BroadcastReceiver 或 IntentService)并传递一些参数,如 notificationId 和 isDismissed,然后在 BroadcastReceiver 中完成您的工作。

你可以在this答案中看到完整的代码。

【讨论】:

    【解决方案2】:

    我不认为有一个听众对此。但是您可以使用PendingIntentBroadcastReceiver 以另一种方式实现此逻辑

    对于 OnClick

    添加ContentIntentBroadcastReceiver。这样你就会知道BroadcastReceiver中的通知是否被点击了

         Intent onClickIntent = new Intent(this, OnClickBroadcastReceiver.class);
         PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, onClickIntent, 0);
         mBuilder.setContentIntent(onClickPendingIntent);
    

    BroadcastReceiver 中你可以编写你的逻辑

     public class OnClickBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
           //Open your activity here
            Intent mainIntent = new Intent(context, YourActivity.class);
            context.startActivity(mainIntent);
    
            // Do your onClick related logic here
        }
    
    }
    

    对于 onDismiss

    为此,您需要在通知生成器中添加DeleteIntent

     Intent onCancelIntent = new Intent(this, OnCancelBroadcastReceiver.class);
                PendingIntent onDismissPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, onCancelIntent, 0);
                mBuilder.setDeleteIntent(onDismissPendingIntent);
    

    BroadcastReceiver 这是

        public class OnCancelBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
        //Do your logic here
        }
    
    }
    

    别忘了将这些BroadcastReceiver注册到AndroidManifest

    【讨论】:

    • 您的 PendingIntent 用于 FLAG_UPDATE_CURRENT。该问题要求每个通知。
    猜你喜欢
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2018-05-26
    • 2010-11-23
    相关资源
    最近更新 更多