0

in the project that I got to work on there's a use of Broadcast receivers. Now, those receivers are registered in the Manifest and also there's this method:

private static void enableComponent(Context context, Class<?> component) {

    ComponentName connectionReceiverComponent = new ComponentName(context, component);
    context.getPackageManager().setComponentEnabledSetting(connectionReceiverComponent, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}

I'm a bit confused about it, because since Android 8 we can't register receivers in the Manifest anymore, instead we have to use runtime registration, using context.registerReceiver(), thus it is not necessary even to put the receivers in the Manifest. And yet, the registration that uses ComponentName still works on Android 8 and Android 9. Can you please explain what's difference between those two methods, and why it works and Android 8 and beyond?

Keselme
  • 3,779
  • 7
  • 36
  • 68

1 Answers1

0

In Activity you can register like this.

private BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState){

  IntentFilter filter = new IntentFilter();
  filter.addAction("SOME_ACTION"); 

  receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      //do something based on the intent's action
    }
  };
     registerReceiver(receiver, filter);
}

Or in your ActivityManifest

<receiver
 android:name=".ConnectivityBroadcastReceiver">
<intent-filter>
  <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
GSutey
  • 136
  • 6