Android – Krunk4Ever! https://www.krunk4ever.com/blog After eliminating all other possibilities, the one remaining-no matter how unlikely-must be the truth. Mon, 22 Apr 2013 07:24:33 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.7 BluetoothAdapter.getDefaultAdapter() throws RuntimeException: Can’t create handler inside thread that has not called Looper.prepare() https://www.krunk4ever.com/blog/2013/02/22/bluetoothadapter-getdefaultadapter-throws-runtimeexception-cant-create-handler-inside-thread-that-has-not-called-looper-prepare/ https://www.krunk4ever.com/blog/2013/02/22/bluetoothadapter-getdefaultadapter-throws-runtimeexception-cant-create-handler-inside-thread-that-has-not-called-looper-prepare/#comments Fri, 22 Feb 2013 22:59:41 +0000 http://www.krunk4ever.com/blog/?p=4388 Continue reading "BluetoothAdapter.getDefaultAdapter() throws RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()"

]]>
So I’m using some hardware SDK that attempts to scan for bluetooth devices on Android and hit into this exception below when calling: BluetoothAdapter.getDefaultAdapter()

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    at android.os.Handler.<init>(Handler.java:121)
    at android.bluetooth.BluetoothAdapter$1.<init>(BluetoothAdapter.java:984)
    at android.bluetooth.BluetoothAdapter.<init>(BluetoothAdapter.java:984)
    at android.bluetooth.BluetoothAdapter.getDefaultAdapter(BluetoothAdapter.java:329)

After researching this problem, it turns out there’s a bug in Android (which apparently still exists in Android 4.0: Ice Cream Sandwich according to the discussions I’ve been reading). The bug is during the initialization of the default adapter, there exists UI code which means it needs to be ran on the UI thread.

Update 2013/04/22: Martin has brought to my attention that as long as you call BluetoothAdapter.getDefaultAdapter() inside any thread that has already called Looper.prepare(), it should work. It doesn’t have to be the UI thread.

I was attempting to use AsyncTask to search for bluetooth devices in the background. Workaround suggest running the code in the main thread or using Handler so that code is queued in the main thread. Unfortunately both solutions block the UI thread and what you see is a progress dialog with a spinner that stops spinning.

It turns out however if you call BluetoothAdapter.getDefaultAdapter() in the main UI thread, calling it subsequently no longer crashes, even in background threads.

Hope that helps!

]]>
https://www.krunk4ever.com/blog/2013/02/22/bluetoothadapter-getdefaultadapter-throws-runtimeexception-cant-create-handler-inside-thread-that-has-not-called-looper-prepare/feed/ 10