版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cc_want/article/details/80995751
将原本运行在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);
}