BluetoothAdapter.getDefaultAdapter() throwing RuntimeException while not in Activity

前端 未结 5 453
天涯浪人
天涯浪人 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:25

    Calling BluetoothAdapter.getDefaultAdapter() in the UI thread works, but is not very practical. I have tried the workaround with a fake Activity, but since I hate such workarounds, I decided to READ what the error message really says and it is nothing more than that the thread didn't call Looper.prepare().

    So calling Looper.prepare() just before calling BluetoothAdapter.getDefaultAdapter() should solve the problem anywhere, not just in a UI thread.

    Works fine for me so far.

提交回复
热议问题