【发布时间】:2017-07-13 06:52:56
【问题描述】:
我有一个应用推送通知。当用户点击通知时,我希望触发广播接收器而不是活动。
我查看了这些线程,看起来这是完全可能的并且很常见。
Android Notification Action is not fired (PendingIntent)
Send broadcast on notification click
但是我无法让它工作。我看到了通知,但是当我点击它时,它永远不会触发我的广播接收器。
这是我尝试过的:
-
我创建了一个自定义接收器:
public class NotificationOnClickReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { Log.d(Constants.Engine.LOGGER_TAG_GCM, NotificationOnClickReceiver.class.toString() + " triggered"); } } -
我在我的全局应用程序(不是活动)上动态注册了这个接收器
mNotificationOnClickReceiver = new NotificationOnClickReceiver(); IntentFilter intentFilterOnClick = new IntentFilter(Constants.Engine.BROADCAST_RECEIVER_FILTER_NOTIFICATION_ONCLICK); getApplicationContext().registerReceiver(mNotificationOnClickReceiver, intentFilterOnClick); Log.e(Constants.Engine.LOGGER_TAG_DBG, "mNotificationOnClickReceiver = " + mNotificationOnClickReceiver.toString());
过滤器只是一个字符串常量(不知道是不是这个问题)
public static final String BROADCAST_RECEIVER_FILTER_NOTIFICATION_ONCLICK = "push_notification.onclick";
-
接收者意图设置:
// When the user taps on the notification bar, this is the receiver that I want to be called Intent pushNotificationIntent; Log.e(Constants.Engine.LOGGER_TAG_DBG, "Notification called!"); pushNotificationIntent = new Intent(this, NotificationOnClickReceiver.class); // Not sure if this causing the problem pushNotificationIntent.setAction(Constants.Engine.BROADCAST_RECEIVER_FILTER_NOTIFICATION_ONCLICK); // ensures that each notification and intent are unique int uniqueCode = new Random().nextInt(Integer.MAX_VALUE); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, uniqueCode, pushNotificationIntent, // Receiver Intent PendingIntent.FLAG_CANCEL_CURRENT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context) .setSmallIcon(mIconId) .setContentTitle(context.getString(R.string.myString)) .setContentText("My GCM Alert!") .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); -
从日志来看,除了我的广播接收器永远不会被调用之外,一切似乎都正常:
02-22 15:47:47.092 16863-16863/com.myapp.test E/MYAPP_DBG: mNotificationOnClickReceiver = mytest.broadcastreceivers.NotificationOnClickReceiver@d78f559 02-22 15:47:53.312 16863-17038/com.myapp.test E/MYAPP_DBG: Notification called!
如果有人有这个工作,你能指出一个示例代码吗?我没有看到我的错误在哪里。
谢谢!
【问题讨论】:
标签: android android-intent push-notification notifications android-pendingintent