gpt4 book ai didi

android - BluetoothAdapter.getDefaultAdapter() 在不在 Activity 中时抛出 RuntimeException

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:35:26 24 4
gpt4 key购买 nike

当我不在 Activity 中但在 TimerTask(在 Service 中创建)中尝试获取默认蓝牙适配器时,使用:

BluetoothAdapter.getDefaultAdapter();

我得到以下异常:

Exception while invoking java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

我的应用程序没有任何 Activity - 那么有没有可能让这个适配器远离 Activity?

最佳答案

这似乎是 Android 中的一个错误,并且在 Android 4.0 (Ice Cream Sandwich) 中仍然存在

要解决此问题并能够从工作线程(例如 AsyncTask)调用 BluetoothAdapter.getDefaultAdapter(),您只需调用 BluetoothAdapter.getDefaultAdapter() 在主 UI 线程上一次(例如在当前 Activity 的 onCreate() 中)。

RuntimeException 仅在初始化期间抛出,BluetoothAdapter.getDefaultAdapter() 仅在您第一次调用它时初始化。对它的后续调用将成功,即使在后台线程中也是如此。

关于android - BluetoothAdapter.getDefaultAdapter() 在不在 Activity 中时抛出 RuntimeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5920578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com