Question:
How can I manage (Connect, Read, Write, Disconnect) a bluetooth connection that persists through configuration changes?
Prefer solutions that are compatible with device version 2.2 "Froyo" using ActionBarSherlock.
Problems...
Neither
BluetoothDevice
norBluetoothSocket
can be retained inonSaveState
.In order to keep my app responsive, the 12 second blocking call
BluetoothSocket.connect()
must be made on a separate thread. Starting aRunnable
is the recommended way to thread long tasks, but it's a nightmare trying to recover on a configuration change. The official docs point to three different solutions.Use
getLastNonConfigurationInstance()
, which is deprecated (seriously?!).Set
android:configChanges="keyboardHidden|orientation"
like the BluetoothChat Sample. However, this does not account for all types of configuration changes.Cancel & restart tasks like the Shelves Example. In this case, this could potentially waste another 12 seconds.
Update 1
Further research led me to asyncTaskLoader, but it seems like this can only update the UI on completion, and cannot provide updates.
The BluetoothHDP sample uses a service. Services seem focused on inter-process communication and the need to persist beyond the activity life-cycle. I don't need either of these features.
Update 2
As pointed out by Reuben, Fragment.setRetainInstance(bool)
has replaced the deprecated getLastNonConfigurationInstance()
. At this point, it seems like the best option is to make a persistent non-UI fragment using setRetainInstance(true)
.