BluetoothAdapter.getDefaultAdapter() 在不在活动中时抛出 RuntimeException [英] BluetoothAdapter.getDefaultAdapter() throwing RuntimeException while not in Activity

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

问题描述

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

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();

我收到以下异常:

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 中的一个错误,并且在 Android 4.0 (Ice Cream Sandwich) 中仍然存在

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

要解决此问题并能够从工作线程(例如 AsyncTask)调用 BluetoothAdapter.getDefaultAdapter(),您只需调用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆