1. 程式人生 > >BluetoothAdapter:Unhandled exception: java.lang.RuntimeException: Can't create handler inside thread

BluetoothAdapter:Unhandled exception: java.lang.RuntimeException: Can't create handler inside thread

將原本執行在6.0上的程式安裝在4.4的系統上之後出現了一個詭異的異常

BluetoothAdapter:Unhandled exception: java.lang.RuntimeException: Can't create handler inside thread

分析原因發現:

1.在Android 6.0 系統中使用BLE掃描BluetoothAdapter.LeScanCallback回撥方法是執行在主執行緒的

2.然而在Android 4.4 系統中,通過列印日誌發現BluetoothAdapter.LeScanCallback的回撥是執行在了子執行緒

3.然而我在BluetoothAdapter.LeScanCallback回撥方法中,因為建立你了Handler所以導致了此異常的出現

解決方法有兩種如下:

第一種方案:修改Hander構造方法,改為

new Handler(Looper.getMainLooper());
第二種方案:在BluetoothAdapter.LeScanCallback中使用Handler傳送訊息
    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        Message msg = new Message();
        msg.obj = device;
        msg.what = 1;
        mHandler.sendMessage(msg);
    }