2015-04-03 57 views
2

我開始了藍牙低能量掃描在MainActivity:安卓藍牙低功耗回調(LeScanCallBack)在單獨的線程?

public class MainActivity extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     BLEScanner.start(bluetoothManager.getAdapter()); 
    } 
} 

(靜態)BLEScanner類如下:

public class BLEScanner {  
    public static void start(final BluetoothAdapter bluetoothAdapter) { 
     bluetoothAdapter.startLeScan(mLeScanCallback); 
    } 

    private static BluetoothAdapter.LeScanCallback mLeScanCallback = 
      new BluetoothAdapter.LeScanCallback() { 
       @Override 
       public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) { 
        String name = device.getName(); 
        String address = device.getAddress(); 
        Log.d("BLESCANNER", name+" "+address); 
        try { 
         Thread.sleep(1000); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
       } 
      }; 
} 

在BLEScanner的Thread.sleep()方法會導致UIThread沒有反應。我如何在單獨的課程中運行BLEScanner類?

回答

0
private BluetoothAdapter.LeScanCallback mLeScanCallback = 
     new BluetoothAdapter.LeScanCallback() { 
      @Override 
      public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) { 
       new Thread(new Runnable() { 
        @Override 
        public void run() { 
         //The code here is executed on on new thread everytime 
         Log.e("LeScanCallback", Thread.currentThread().getName());//Prints Thread-xxxx 
        } 
       }).start(); 
      } 
     };