title: Android Bluetooth device scan/discovery for CLassic and Low Energy Devices sequentially
body: <p>I am developing an Android app which searches for Classic and Low Energy Bluetooth devices such that when I press "search" button it will show me all Bluetooth devices (low energy and classic) in range. Since classic BT discovery and LE scanning are different things, I have to implement them separately and combine them in one function such that</p>
  
  <p>searchFirstLowEnergyThenClassic() or searchFirstClassicThenLowEnergy()</p>
  
  <p>In order to implement this, I have to know when the discovery/scanning ends so that I immediately start scan/discovery for other technology.</p>
  
  <p>Here is my implementation:</p>
  
  <ol>
  <li>Started Classic BT discovery</li>
  <li>Received BluetoothAdapter.ACTION_DISCOVERY_FINISHED</li>
  <li>Started BLE Scaning -> onReceive action equals(ACTION_DISCOVERY_FINISHED)</li>
  <li>Stop search when BLE Scan ended</li>
  </ol>
  
  <p>This looks ok but there is a problem when I extend the behavior. When I want search, I start searching first with LE scan or Classic discovery based on the last connected technology. For example if last time the device is connected to a Classic BT device, searchFirstClassicThenLowEnergy() is run. Otherwise, searchFirstLowEnergyThenClassic().</p>
  
  <p>So as you might guess, it gets more complicated. For example, when the Classic BT discovery ends, the app should know whether the search ended or it should proceed with LE scan. </p>
  
  <p>There is also this issue. When the user stops search during the scan/discovery of first technology, it will recieve BluetoothAdapter.ACTION_DISCOVERY_FINISHED but it shouldn't start LE scan since the search is terminated by user.</p>
  
  <p>I implemented this using some flags (not working properly, though) but my code looks very dirty.</p>
  
  <pre><code>else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
              // Classic Bluetooth discovery ended
              lastOpenedType = getLastOpenedType();
              if (lastOpenedType == BT_CLASSIC &amp;&amp; !isSearchStoppedByUser()) {
                  // Search should continue with low energy scan
                  startBtLeScanning();
              } else if (lastOpenedType != BT_CLASSIC &amp;&amp; !isSearchStoppedByUser()){
                  // Search ended
                  searchProgressLayout.setVisibility(View.INVISIBLE);
              } else {
                  // Search ended by user
                  searchProgressLayout.setVisibility(View.INVISIBLE);
              }
        }
  </code></pre>
  
  <p>In short, I am asking if someone has a more brilliant and simple solution on this?</p>
  
  <p>PS. A solution without broadcast intent is much appreciated if possible.</p>