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

Koc*_*cus 12 android bluetooth runtimeexception

当我试图获取默认蓝牙适配器时,我不在活动中,但在TimerTask(在内部创建Service)使用:

BluetoothAdapter.getDefaultAdapter();
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

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

我的应用程序没有任何活动 - 所以有没有可能让这个适配器远离Activity?

Tol*_*Hon 14

这似乎是Android中的一个错误,仍然存在于Android 4.0(冰淇淋三明治)中

要解决此问题并且能够BluetoothAdapter.getDefaultAdapter()从工作线程(例如AsyncTask)调用,您所要做的就是BluetoothAdapter.getDefaultAdapter()在主UI线程上调用一次(例如onCreate(),在当前活动的内部).

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


Mar*_*oza 6

调用BluetoothAdapter.getDefaultAdapter()UI线程工作,但不是很实用.我已尝试使用假活动的解决方法,但由于我讨厌这样的解决方法,我决定阅读错误消息真正说的内容,它只不过是线程没有调用Looper.prepare().

所以在调用Looper.prepare()之前调用BluetoothAdapter.getDefaultAdapter()应该可以在任何地方解决问题,而不仅仅是在UI线程中.

到目前为止对我来说工作正常.