1

我正在创建一个具有蓝牙连接的应用程序。我创建了一个库,每次连接丢失/失败/建立/等时都使用回调。关于连接的一切工作都很好,但我很难处理方向变化。当设备改变方向时,我希望连接保持打开状态。同时我希望在用户关闭应用程序时关闭连接。我为此设计的 API 级别是 API 5-10。以下是我遇到的问题:

  1. 如果我关闭我onDestroy()的连接,连接将在每次​​关闭应用程序时关闭,但不会在应用程序暂停时关闭(所需的输出)。但是,onDestroy()只要应用程序方向发生变化,就会调用它。这导致了问题 #2。

  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().

我想我想知道两件事:

  1. 一开始是onRetainNonConfigrationInstance()处理这个问题的好方法吗?
  2. 有没有更优雅的方法来保持连接打开直到应用程序关闭?我考虑过创建一个像 onRetainCalled 这样的布尔值来防止关闭,但对我来说它看起来很丑(而且可能不可靠)。
4

1 回答 1

1

最理想的情况是,您应该将您的蓝牙连接代码放入Service:我使用这个,它非常好。您可以打开多个活动,而无需考虑它。

于 2011-09-12T19:13:25.517 回答