Broadcast Receiver Not Working in Android Oreo

Broadcast Receivers not working in background in android oreo and pie

Beginning with Android 8.0 (API level 26), the system imposes
additional restrictions on manifest-declared receivers.

If your app targets Android 8.0 or higher, you cannot use the manifest
to declare a receiver for most implicit broadcasts (broadcasts that
don't target your app specifically). You can still use a
context-registered receiver when the user is actively using your app.

I guess system automatically unregisters your broadcast receivers when you close the app.
Solution: Create sticky or foreground service and register your broadcast receiver in service. When you receive broadcast, launch activity and show dialog box from broadcast receiver onReceive.

Broadcast receiver for nought and Oreo + devices not working

You can not register broadcast receiver in manifest.xml from Oreo.
You can see
Android 8.0 Behavior Changes

Apps cannot use their manifests to register for most implicit
broadcasts (that is, broadcasts that are not targeted specifically at
the app).

Solution

Register your receiver in your related Activity instead. Like this.

public class MainActivity extends AppCompatActivity {
BroadcastReceiver receiver;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction("android.intent.action.LOCKED_BOOT_COMPLETED");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// todo
}
};
registerReceiver(receiver, filter);
}

@Override
protected void onDestroy() {
super.onDestroy();
if (receiver != null)
unregisterReceiver(receiver);
}
}

You can add action as string same as manifest, if you don't find relevant constant string.

Broadcast Receiver on Android Oreo

It's not supported in Oreo as manifest tag, you must have to register it at an Service/ Activity with context.registerReceiver(). Or you use the WorkManager to schedule something for specific network conditions.



Related Topics



Leave a reply



Submit