本文介绍了BluetoothAdapter.getDefaultAdapter()抛出的RuntimeException,而不是活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我试图让默认的蓝牙适配器,我不在的活动,但在的TimerTask 服务)使用:

When I'm trying to get default bluetooth adapter while i'm NOT in Activity, but in TimerTask (created inside Service) by using:

BluetoothAdapter.getDefaultAdapter();

我得到以下异常:

I get the following exception:

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

我的应用程序没有任何活动 - 那么,有没有可能得到这个适配器远离活动

My application do not have any activity - so is there any possibility to get this adapter away from Activity?

推荐答案

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

This appears to be a bug in Android and still exists in Android 4.0 (Ice Cream Sandwich)

要解决此,并可以调用 BluetoothAdapter.getDefaultAdapter()从工作线程(如AsyncTask的),你所要做的就是调用 BluetoothAdapter.getDefaultAdapter()一旦主UI线程上(如在的onCreate()你当前活动的)。

To workaround this and be able to call BluetoothAdapter.getDefaultAdapter() from a worker thread (e.g. AsyncTask), all you have to do is call BluetoothAdapter.getDefaultAdapter() once on the main UI thread (e.g. inside the onCreate() of your current activity).

该RuntimeException的初始化期间只扔了, BluetoothAdapter.getDefaultAdapter()仅初始化第一次调用它。随后调用它会成功,即使是在后台线程。

The RuntimeException is only thrown during initialization, and BluetoothAdapter.getDefaultAdapter() only initializes the first time you call it. Subsequent calls to it will succeed, even in background threads.

这篇关于BluetoothAdapter.getDefaultAdapter()抛出的RuntimeException,而不是活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 23:35