title: Android bluetooth scan button
body: <p>onCreate, I check whether bluetooth is enabled. If not, prompt user to switch it on.</p>
  
  <p>If during initial launch request to enable BT but the user selects no and proceeds to press the scan button, the app will crash. I do see the BT request dialog firing afterwards though.</p>
  
  <p>If during initial launch request to enable BT but the user selects yes, the scan button does nothing though the <code>else</code> branch of my button click gets fired.</p>
  
  <p>The button works fine if bluetooth is switched on before opening the app.</p>
  
  <pre><code>@Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      init();
  
      if (btAdapter == null) {
          Toast.makeText(getApplicationContext(), "No bluetooth detected", Toast.LENGTH_SHORT).show();
          finish();
      } else {
          if (!btAdapter.isEnabled()) { // if BT not enabled, request to turn on BT.
              Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
              startActivityForResult(intent, 1);
          }
         // getPairedDevices();
      }
      mHandler = new Handler();
  }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if(resultCode == RESULT_CANCELED){
          Toast.makeText(getApplicationContext(),"Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
          finish();
      }
  
  private void init() {
      // Get a reference to button
      final Button btnScanNew = (Button) findViewById(R.id.btnScanNew);
      //Set the click listener
      btnScanNew.setOnClickListener(new View.OnClickListener(){
          @Override
          public void onClick(View view) { // Scan for new bluetooth devices
              btAdapter.cancelDiscovery();
              btAdapter.startDiscovery();
          }
      });
  
      listView = (ListView) findViewById(R.id.listView);
      listView.setOnItemClickListener(this);
      listAdapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_list_item_1, 0);
      listView.setAdapter(listAdapter);
      btAdapter = BluetoothAdapter.getDefaultAdapter();
      pairedDevices = new ArrayList&lt;String&gt;();
      filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
      receiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
              String action = intent.getAction();
              //Finding devices
              if(BluetoothDevice.ACTION_FOUND.equals(action)){
                  // Get the BluetoothDevice object from the Intent
                  BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  
                  String s ="";
                  for (int a = 0; a &lt; pairedDevices.size(); a++){
                      if(device.getName().equals(pairedDevices.get(a))){
                          //append
                          s = "(Paired)";
                          break;
                      }
                  }
                  // Add the name and address to an array adapter to show in a ListView
                  listAdapter.add(device.getName()+" "+s+" "+"\n" +device.getAddress());
              }
              else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                  listAdapter.clear(); // clear the list of existing scanned devices
                  btnScanNew.setText("Scanning");
                  btnScanNew.setEnabled(false);
  
              }
              else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                  btnScanNew.setEnabled(true);
                  btnScanNew.setText("Scan");
              }
              else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                  if(btAdapter.getState() == btAdapter.STATE_OFF){
                      Intent intent2 = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                      startActivityForResult(intent2, 1);
                  }
              }
          }
      };
      registerReceiver(receiver, filter);
      filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
      registerReceiver(receiver, filter);
      filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
      registerReceiver(receiver, filter);
      filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
      registerReceiver(receiver, filter);
  }
  </code></pre>
  
  <p>Declared the following to detect request code.</p>
  
  <pre><code>private static final int INITIAL_REQUEST_ENABLE_BT = 9 ;
  private static final int SCAN_BTN_REQUEST_ENABLE_BT = 10 ;
  </code></pre>
  
  <p>Edited <code>onCreate()</code> &amp; <code>onActivityResult()</code></p>
  
  <pre><code>protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      init();
  
      if (btAdapter == null) {
          Toast.makeText(getApplicationContext(), "No bluetooth detected", Toast.LENGTH_SHORT).show();
          finish();
      } else {
          if (!btAdapter.isEnabled()) { // if BT not enabled, request to turn on BT.
              Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
              startActivityForResult(intent, INITIAL_REQUEST_ENABLE_BT);
          }
         // getPairedDevices();
      }
      mHandler = new Handler();
  }
  
  
  
   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case INITIAL_REQUEST_ENABLE_BT:
                if (resultCode == Activity.RESULT_CANCELED) {
                    Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
                    //finish();
                }
                break;
            case SCAN_BTN_REQUEST_ENABLE_BT:
                if (resultCode == Activity.RESULT_OK) { // if request from scan btn and user enabled bluetooth. Start discovery immediately.
                    Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
                    // open the discovery
                    btAdapter.cancelDiscovery();
                    btAdapter.startDiscovery();
                }
                break;
        }
    }
  </code></pre>
  
  <p>Edited button</p>
  
  <pre><code>   btnScanNew.setOnClickListener(new View.OnClickListener(){
          @Override
          public void onClick(View view) { // Scan for new bluetooth devices
              if (!btAdapter.isEnabled()) {
                  Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                  startActivityForResult(enableIntent, SCAN_BTN_REQUEST_ENABLE_BT);
              }
              else{
                  Toast.makeText(MainActivity.this, "BT already enabled, scanning now...", Toast.LENGTH_LONG).show();
                  btAdapter.cancelDiscovery();
                  btAdapter.startDiscovery();
              }
          }
      });
  </code></pre>
  
  <p><strong>For simplicity sake, I have removed the initial "upon-launch-check".</strong></p>
  
  <p>logcat when I launch app with BT off and clicked the scan button and select 'yes' to on BT. It does on the phone's BT but does no scanning and upon 2nd click it crashes.</p>
  
  <pre><code>                                                                                     java.lang.RuntimeException: Unable to pause activity {com.example.matamatamata.myfirstapp/com.example.matamatamata.myfirstapp.MainActivity}: java.lang.IllegalArgumentException: Receiver not registered: com.example.matamatamata.myfirstapp.MainActivity$3@373702de
                                                                                       at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3732)
                                                                                       at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3691)
                                                                                       at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3666)
                                                                                       at android.app.ActivityThread.access$1100(ActivityThread.java:177)
                                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1459)
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                       at android.os.Looper.loop(Looper.java:145)
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:5938)
                                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
                                                                                    Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.example.matamatamata.myfirstapp.MainActivity$3@373702de
                                                                                       at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:822)
                                                                                       at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:2025)
                                                                                       at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:528)
                                                                                       at com.example.matamatamata.myfirstapp.MainActivity.onPause(MainActivity.java:187)
                                                                                       at android.app.Activity.performPause(Activity.java:6446)
                                                                                       at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1308)
                                                                                       at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3718)
                                                                                       at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3691) 
                                                                                       at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3666) 
                                                                                       at android.app.ActivityThread.access$1100(ActivityThread.java:177) 
                                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1459) 
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                       at android.os.Looper.loop(Looper.java:145) 
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:5938) 
                                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                                       at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389) 
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184) 
  </code></pre>