3

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?

mind
  • 382
  • 6
  • 18
  • @kelalaka Where, in the broadcast class? What should be the content? – mind Oct 26 '18 at 22:10
  • on activity. onDestroy may never be called. [OnDestroy](https://stackoverflow.com/questions/18361719/android-activity-ondestroy-is-not-always-called-and-if-called-only-part-of-the) – kelalaka Oct 26 '18 at 22:16
  • But as you can see, im logging "Service onDestroy" and im seeing this. But im not getting to "Service stops, restarting service..." – mind Oct 26 '18 at 22:30
  • Use the [START_STICKY](https://developer.android.com/reference/android/app/Service.html#START_STICKY) flag instead when starting the service to make it restart itself in case it is stopped. – daka Oct 27 '18 at 21:24
  • @daka Already doing that, service is still killed. – mind Oct 27 '18 at 21:47

1 Answers1

3

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!

Rodrigo Ehlers
  • 1,581
  • 8
  • 25
  • This seems to apply to my case. Its also mentioned in the developers guide: https://developer.android.com/guide/components/broadcasts – mind Oct 27 '18 at 21:50