Search code examples
androidbroadcastreceiverandroid-broadcastreceiverandroid-8.0-oreogoogle-awareness

Awareness API & Android O using BroadcastReceiver


I have an Android app which uses the Awareness API to setup a fence when a headset is plugged in.

I have implemented the AwarenessFence using code much like in the examples at: https://developers.google.com/awareness/android-api/fence-register.

I have a PendingIntent defined as:

PendingIntent.getBroadcast(context, 0, new Intent("my.application.packageFENCE_RECEIVER_ACTION"), 0)

Then in my AndroidManifest.xml file I have

<receiver android:name=".fence.FenceDetector$MyFenceReceiver">
<intent-filter>
    <action android:name="my.application.packageFENCE_RECEIVER_ACTION" />
</intent-filter>

This is declared in the Manifest due to the fact that I want to receive broadcasts even when my app is in the background.

This all worked fine on Android 7.0 and below, but when I run this on a Android 8.0 I get the error:

BroadcastQueue: Background execution not allowed: receiving Intent { act=my.application.packageFENCE_RECEIVER_ACTION

I assume this is due to the new restrictions for background execution on Android O.

Can anybody tell me how to register a broadcast receiver which can listen to awareness fence triggers when in the background on a Android device running API 26.

Let me know If there is something which is unclear or if I need to elaborate something.

Thanks in advance


Solution

  • I can't test it on device now, but from all I've read, the limitation is only on implicit broadcasts. That means, if you create a explicit broadcast instead, that's all you need to make it work.

    That means instead of this:

    // implicit intent matching action
    PendingIntent.getBroadcast(context, 0,
        new Intent("my.application.packageFENCE_RECEIVER_ACTION"), 0)
    

    you do that:

    // explicit intent directly targeting your class
    PendingIntent.getBroadcast(context, 0,
        new Intent(context, FenceDetector.MyFenceReceiver.class), 0)