Android蓝牙低功耗回调(LeScanCallBack)在单独的线程上?

时间:2015-04-03 09:12:49

标签: android multithreading bluetooth callback

我在MainActivity中启动蓝牙低功耗扫描:

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类?

1 个答案:

答案 0 :(得分: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();
            }
        };