My BroadcastReceiver seems to not be receiving the intent it is listening for.
I'm starting a background service which has to run all the time. Whenever the service is killed it sends an intent to my BroadcastReceiver which then restarts the service.
Here's the onDestroy
of my service:
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy");
sendBroadcast(new Intent("com.myapp.app.RESTART_SERVICE"));
stoptimertask();
super.onDestroy();
}
Here's my BroadcastReceiver:
public class RestarterBroadcastReceiver extends BroadcastReceiver {
public RestarterBroadcastReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Service stopped, restarting...");
context.startService(new Intent(context, ActivityRecognitionService.class));
}
}
And the important bit of the Android Manifest:
<receiver
android:name=".RestarterBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.myapp.app.RESTART_SERVICE"/>
</intent-filter>
</receiver>
Why isn't my BroadcastReceiver receiving the intent?
Your problem might be that Android Oreo effectively banned implicit broadcasts. The easiest way for you to fix this is to use an explicit broadcast instead of an implicit one.
Try changing the onDestroy
code of your service to the following:
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy");
// Here you're using an explicit intent instead of an implicit one
sendBroadcast(new Intent(getApplicationContext(), RestarterBroadcastReceiver.class));
stoptimertask();
super.onDestroy();
}
As you're not using the intent action anymore, you can also change your Android Manifest to the following:
<receiver
android:name=".RestarterBroadcastReceiver"
android:enabled="true"
android:exported="true">
</receiver>
Hope this helps!
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