0

我有一个将使用 2 个活动的应用程序。开始或主要活动设置蓝牙连接。当我切换到另一个活动时,我失去了蓝牙连接。切换时能否保持蓝牙连接?这是 OnResume() 和 onPause()。当我在 onPause 中删除 btSocket.close() 时,连接被保持,但在 onResume 尝试连接时不会通信。

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
  if(Build.VERSION.SDK_INT >= 10){
      try {
          final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
          return (BluetoothSocket) m.invoke(device, MY_UUID);
      } catch (Exception e) {
          Log.e(TAG, "Could not create Insecure RFComm Connection",e);
      }
  }
  return  device.createRfcommSocketToServiceRecord(MY_UUID);
  }

  @Override
  public void onResume() {
  super.onResume();

  Log.d(TAG, "...onResume - try connect...");

  BluetoothDevice device = btAdapter.getRemoteDevice(address);


try {
    btSocket = createBluetoothSocket(device);
} catch (IOException e) {
    errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}

 btAdapter.cancelDiscovery();

try {
  btSocket.connect();
  Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
  try {
    btSocket.close();
  } catch (IOException e2) {
    errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
  }
}

// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");

mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}

@Override
public void onPause() {
super.onPause();

Log.d(TAG, "...In onPause()...");

try     {
  btSocket.close();
} catch (IOException e2) {
  errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
4

1 回答 1

0

您应该使您的蓝牙连接独立于您的活动。我建议您将所有蓝牙代码放入从 Android 应用程序类派生的“MyApp”类或服务中。使用服务会更复杂,但它会为您提供即使在用户关闭活动后仍保持应用程序运行的选项,例如,如果您想完成蓝牙通信。

你会发现很多关于这两个选项的文章,因为它们是构建应用程序的常用方法——尤其是当存在某种形式的网络通信时。

于 2013-09-24T01:52:40.360 回答