title: Programmatically enable/disable Broadcastreceiver
body: <p>We have an app that scans for Bluetooth devices. The code responsible for scanning should only run when bluetooth is enabled. Also we want to disable/enable this feature at any point in time.</p>
  
  <p>We choose to implement a BroadcastReceiver that registers for the BluetoothAdapter.ACTION_STATE_CHANGED broadcast.</p>
  
  <p>Here some of the problems we encountered:</p>
  
  <p><strong>Programmatically enable the BroadcastReceiver:</strong></p>
  
  <pre><code>public void registerForBroadcasts(Context context) {
      IntentFilter bluetooth = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
      context.registerReceiver(this, bluetooth);
  }
  </code></pre>
  
  <ol>
  <li>When the app is killed, the BroadcastReceiver is also not active anymore. So if the user multi-tasks-swipes the app to death, it is not being woken up again.</li>
  <li>We have full control, when to start the BroadcastReceiver.</li>
  </ol>
  
  <p><strong>Declare the BroadcastReceiver in the Manifest</strong></p>
  
  <pre><code>&lt;receiver android:name="com.mypackage.BroadcastReceiver"&gt;
      &lt;intent-filter&gt;
          &lt;action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/&gt;
      &lt;/intent-filter&gt;
  &lt;/receiver&gt;
  </code></pre>
  
  <ol>
  <li>The BroadcastReceiver is active right after the app start.</li>
  <li>The BroadcastReceiver cannot be disabled.</li>
  </ol>
  
  <p><strong>Declare the BroadcastReceiver in the Manifest as disabled + enable it programmatically</strong></p>
  
  <pre><code>&lt;receiver android:name="com.mypackage.BroadcastReceiver"
            android:enabled="false" &gt;
      &lt;intent-filter&gt;
          &lt;action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/&gt;
      &lt;/intent-filter&gt;
  &lt;/receiver&gt;
  </code></pre>
  
  <p>Then enable the component if you need it.</p>
  
  <pre><code>public void registerForBroadcasts(Context context) {
      ComponentName component = new ComponentName(context, BroadcastReceiver.class);
      PackageManager pm = context.getPackageManager();
      pm.setComponentEnabledSetting(
                  component,
                  PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                  PackageManager.DONT_KILL_APP);
  }
  </code></pre>
  
  <p>My tests have shown, the state is persisted with the system, so the BroadcastReceiver will stay enabled. It combines the advantages of both methods.</p>
  
  <ol>
  <li>BroadcastReceiver can be disabled</li>
  <li>BroadcastReceiver can be on or off by default</li>
  <li>BroadcastReceiver keeps activation even if app is disabled and phone rebooted.</li>
  </ol>
  
  <p>Am I missing something, does this method seem legit?</p>