简体   繁体   中英

Static BroadcastReceiver not receiving custom intent

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM