我有一个与推送通知相关的应用程序。当用户点击通知时,我希望触发广播接收器而不是活动。
我查看了这些线程,看起来这是完全可能和常见的。 Android Notification Action is not fired (PendingIntent) Send broadcast on notification click 但是我无法让它工作。我看到通知,但是当我点击它时,它从未触发我的广播接收器。
这是我尝试过的:
我查看了这些线程,看起来这是完全可能和常见的。 Android Notification Action is not fired (PendingIntent) Send broadcast on notification click 但是我无法让它工作。我看到通知,但是当我点击它时,它从未触发我的广播接收器。
这是我尝试过的:
I created a custom receiver:
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"); } }
I registered this receiver dynamically on my global Application (not activity)
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";
Receiver intent setup:
// 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);
From the logs, things seem to work except that my Broadcast receiver never gets called:
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!