以编程方式启用和禁用广播接收器

要启用或禁用 BroadcastReceiver,我们需要获取 PackageManager 的引用,我们需要一个 ComponentName 对象,其中包含我们要启用/禁用的接收器类:

ComponentName componentName = new ComponentName(context, MyBroadcastReceiver.class);
PackageManager packageManager = context.getPackageManager();

现在我们可以调用以下方法来启用 BroadcastReceiver

packageManager.setComponentEnabledSetting(
    componentName,
    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
    PackageManager.DONT_KILL_APP);

或者我们可以使用 COMPONENT_ENABLED_STATE_DISABLED 来禁用接收器:

packageManager.setComponentEnabledSetting(
    componentName,
    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
    PackageManager.DONT_KILL_APP);