我正在创建一个具有蓝牙连接的应用程序。我创建了一个库,每次连接丢失/失败/建立/等时都使用回调。关于连接的一切工作都很好,但我很难处理方向变化。当设备改变方向时,我希望连接保持打开状态。同时我希望在用户关闭应用程序时关闭连接。我为此设计的 API 级别是 API 5-10。以下是我遇到的问题:
如果我关闭我
onDestroy()
的连接,连接将在每次关闭应用程序时关闭,但不会在应用程序暂停时关闭(所需的输出)。但是,onDestroy()
只要应用程序方向发生变化,就会调用它。这导致了问题 #2。如果我使用
onRetainNonConfigurationInstance()
,我可以成功地保持打开的套接字。如果我不关闭套接字onDestroy()
,那么一切正常。但是,当应用程序关闭时,套接字似乎保持打开状态(即其他设备仍在从中读取)。
我目前的设置与此类似:
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();
}
使用当前的实现,套接字将被保存但同时because both onRetainNonConfigurationInstance()
被关闭,就像调用onDestroy()
.
我想我想知道两件事:
- 一开始是
onRetainNonConfigrationInstance()
处理这个问题的好方法吗? - 有没有更优雅的方法来保持连接打开直到应用程序关闭?我考虑过创建一个像 onRetainCalled 这样的布尔值来防止关闭,但对我来说它看起来很丑(而且可能不可靠)。