best way to handle orientation change with bluetooth sockets
I'm creating an app that has a bluetooth connection. I've created a library that uses callbacks every time a connection is lost/failed/established/etc. Everything about the connection works just fine, but I'm having a hard time handling orientation changes. I want the connection to remain open when the device changes orientation. At the same time I want the connection to close when the user closes the application. The API levels I'm designing this for are APIs 5开发者_运维问答-10. Here's the issues I come across:
If I close my connection on
onDestroy()
, the connection will close every time the app is closed but not when the app is simply paused (desired output). However,onDestroy()
is called whenever the application orientation changes. Which leads to issue #2.If I use
onRetainNonConfigurationInstance()
, I can successfully keep the open socket. If I don't close the socket inonDestroy()
, then everything works just fine. However, the socket seems to remain open when the app closes (i.e. the other devices are still reading from it).
The setup I currently have looks similar to this:
BluetoothConnection btConnection;
@Override
public void onCreate(Bundle icicle)
{
/** Activity setup **/
btConnection = (BluetoothConnection) getLastNonConfigurationInstance();
if(btConnection != null) // we already have a connection from a previous state, let's set it up to work with this state
{
/** Set up the connection since it already exists **/
}
}
@Override
public Object onRetainNonConfigurationInstance()
{
BluetoothConnection saveConnection = btConnection;
return saveConnection;
}
@Override
protected void onDestroy()
{
super.onDestroy()
if(btConnection != null)
btConnection.closeConnection();
}
With this current implementation, the socket will be saved but closed at the same time because both onRetainNonConfigurationInstance()
is called as well as onDestroy()
.
I guess I'd like to know two things:
- Is
onRetainNonConfigrationInstance()
a good way to handle this problem to begin with? - Is there a more elegant way to keep a connection open till an app closes? I've thought about creating a boolean like onRetainCalled to prevent the thing from closing, but it seems ugly to me (and possibly unreliable).
Optimally, you should put your Bluetooth connection code into a Service
: I use this and it is quite excellent. You can open multiple Activities without having to think about it at all.
精彩评论