Click on android notification icon does not trigger broadcast receiver

后端 未结 2 1640
心在旅途
心在旅途 2020-12-11 18:09

I have an app hooked with push notifications. When the user click on the notification, I want a broadcast receiver to be triggered instead of an activity.

I looked a

相关标签:
2条回答
  • 2020-12-11 18:39

    To send a broadcast use this sendBroadcast(new Intent("NotificationClicked"));

    Now to recieve the broadcast, mention this in your manifestunder application tag

    <receiver android:name=".NotificationOnClickReceiver" >
                <intent-filter>
                    <action android:name="NotificationClicked" >
                    </action>
                </intent-filter>
            </receiver>
    
    0 讨论(0)
  • 2020-12-11 19:00

    This would appear to be the problem:

    pushNotificationIntent = new Intent(this, NotificationOnClickReceiver.class);
    

    You're actually creating an explicit Intent for the broadcast PendingIntent. Explicit Intents do not work with dynamically registered Receivers, as they target a Receiver class, rather than an instance.

    You'll need to use an implicit Intent instead, which you can do by simply instantiating the Intent with the action String, rather than a Context and Class. For example:

    pushNotificationIntent = new Intent(Constants.Engine.BROADCAST_RECEIVER_FILTER_NOTIFICATION_ONCLICK);
    

    Please note that if your app's process is killed before the Notification is clicked, that dynamically registered Receiver instance will die, too, and the Notification's broadcast won't really do anything.

    Depending on the desired behavior, it might be preferable to instead statically register your Receiver class in the manifest, and stay with the explicit Intent. Doing this will allow your app to receive the Notification broadcast even if its process has been killed.

    To do that, you'd just need to add a <receiver> element for your NotificationOnClickReceiver in the manifest.

    <receiver android:name="NotificationOnClickReceiver" />
    

    Though you can still set an action on that broadcast Intent, you don't need an <intent-filter> for it here, as the explicit Intent is directly targeting the class anyway. If the Receiver is only for that one function, you don't necessarily need the action, and can just remove that altogether.

    You can then remove the code you have in step 2, as you'd no longer need the dynamically registered instance.

    0 讨论(0)
提交回复
热议问题