2017-05-26 24 views
0

我注意到,在一個可執行文件掃描程序的情況下,掃描停止並在給定的時間段後重新開始,例如每20秒。爲什麼藍牙低能量掃描儀需要重新啓動?

這裏例如是一個掃描儀類在單獨的線程中啓動掃描儀。您可以在start()方法,線程進入睡眠一段時間看,然後掃描儀停止並重新啓動:

public class BleScanner extends Thread { 

    private final BluetoothAdapter bluetoothAdapter; 
    private final BluetoothAdapter.LeScanCallback mLeScanCallback; 

    private volatile boolean isScanning = false; 

    public BleScanner(BluetoothAdapter adapter, BluetoothAdapter.LeScanCallback callback) { 

     bluetoothAdapter = adapter; 
     mLeScanCallback = callback; 
    } 

    public boolean isScanning() { 
     return isScanning; 
    } 

    public void startScanning() { 
     synchronized (this) { 
      isScanning = true; 
      start(); 
     } 
    } 

    public void stopScanning() { 
     synchronized (this) { 
      isScanning = false; 
      bluetoothAdapter.stopLeScan(mLeScanCallback); 
     } 
    } 

    @Override 
    public void run() { 

     try { 

      // Thread goes into an infinite loop 
      while (true) { 

       synchronized (this) { 

        // If there is not currently a scan in progress, start one 
        if (!isScanning) break; 
        bluetoothAdapter.startLeScan(mLeScanCallback); 
       } 

       sleep(Constants.SCAN_PERIOD); // Thread sleeps before stopping the scan 

       // stop scan 
       synchronized (this) { 
        bluetoothAdapter.stopLeScan(mLeScanCallback); 
       } 

       // restart scan on next iteration of infinite while loop 
      } 

     } catch (InterruptedException ignore) { 


     } finally { // Just in case there is an error, the scan will be stopped 

      bluetoothAdapter.stopLeScan(mLeScanCallback); 

      // The finally block always executes when the try block exits. This ensures that the 
      // finally block is executed even if an unexpected exception occurs. 
     } 
    } 
} 

在那裏停止和重新啓動掃描儀的任何好處?爲什麼不讓掃描繼續進行?

回答

1

有優勢。在某些設備上,每次掃描只能看到一次設備的廣告。在一些你會看到所有的廣告。此外,重新開始掃描會清除一些低級別的東西,通常比保持掃描儀始終處於活動狀態更好。