Search code examples
androidbroadcastreceiverandroid-notificationsbackground-processandroid-8.0-oreo

Receiving broadcast from notification on Android Oreo


I have a custom button in a sticky notification.
I used to attach a PendingIntent to it for receiving button clicks:

Intent intent = new Intent();

intent.setAction("com.example.app.intent.action.BUTTON_CLICK");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 2000, intent, PendingIntent.FLAG_UPDATE_CURRENT);
contentViewExpanded.setOnClickPendingIntent(R.id.button, pendingIntent);

When i run this code on Oreo , i get BroadcastQueue: Background execution not allowed in logcat and don't receive button click.

I registered receiver with manifest:

<receiver
    android:name=".BroadcastReceiver.NotificationActionReceiver"
    android:enabled="true"
    android:exported="false">
    <intent-filter>
        <action android:name="com.example.app.intent.action.BUTTON_CLICK"/>
    </intent-filter>
</receiver>

I also tried registering receiver in my code:

NotificationActionReceiver mMyBroadcastReceiver = new NotificationActionReceiver();
IntentFilter filter = new IntentFilter("com.example.app.intent.action.BUTTON_CLICK");
mContext.registerReceiver(mMyBroadcastReceiver, filter);

This works but only when the app is visible to user.

Thanks for help


Solution

  • Never use an implicit Intent when an explicit Intent will work.

    Replace:

    Intent intent = new Intent();
    
    intent.setAction("com.example.app.intent.action.BUTTON_CLICK");
    

    with:

    Intent intent = new Intent(this, NotificationActionReceiver.class);
    

    And remove the <intent-filter> from the NotificationActionReceiver <receiver> element.