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

将原本运行在6.0上的程序安装在4.4的系统上之后出现了一个诡异的异常BluetoothAdapter:Unhandledexception:java.lang.RuntimeException:Ca

by
江江
on
2018/07/11

将原本运行在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);
    }
江江江江于 2026-10-13 11:58:10 修改阅读 23057评论 0点赞 0