BluetoothAdapter.getDefaultAdapter() throwing RuntimeException while not in Activity

前端 未结 5 423
天涯浪人
天涯浪人 2021-01-04 08:39

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

B         


        
5条回答
  •  囚心锁ツ
    2021-01-04 09:12

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

    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).

    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.

提交回复
热议问题