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
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)
I did a little digging around and stumbled upon this blog post by CommonsWare. It states the very problem that you're facing.
From the above post :-
One of the more controversial changes in Android O — for apps with a sufficiently-high targetSdkVersion — is the effective ban on implicit broadcasts.
So, according to this, I don't think your problem has anything to do with the Awareness API. Instead, it's because of the new behaviour introduced in Android 8.
Unfortunately, though, there doesn't seem to be viable solution to this as of now. Again, phrasing from the same post :-
If you are receiving system-sent implicit broadcasts (e.g., ACTION_PACKAGE_ADDED), keep your targetSdkVersion at 25 or lower, until we figure out better workarounds that (hopefully) do not involve polling.
So, hopefully there would be a better solution for 8 in the near future. Meanwhile, you could consider other options or could consider lowering your targetSDK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With