在我的 Android 应用程序中,我设置了两个活动:
我面临的问题是如何从连接活动到控制活动获取已建立的连接(由BluetoothSocket对象表示)。我考虑过使用应用程序类,但我不确定这是否是最好的方法。
有没有办法使用应用程序类来实现这种通信,或者推荐的方法是什么?
所以,首先,让我们创建一个BluetoothViewModel来满足您的要求
第 1 步:创建蓝牙视图模型
在您的项目中,创建一个名为 BluetoothViewModel 的新类。这将扩展 Android 的 ViewModel 类,该类有助于管理 UI 相关组件的数据。
公共类BluetoothViewModel扩展ViewModel { 私有BluetoothSocket bluetoothSocket;
public void setBluetoothSocket(BluetoothSocket socket) {
this.bluetoothSocket = socket;
}
public BluetoothSocket getBluetoothSocket() {
return bluetoothSocket;
}
}
第2步:在连接活动中设置BluetoothSocket
当您在连接活动中成功连接到蓝牙设备并获取BluetoothSocket时,您将其存储在您的BluetoothViewModel中:
// 在您的连接活动中 BluetoothSocket bluetoothSocket = ... // 连接并获取套接字的代码
// 获取蓝牙ViewModel BluetoothViewModel viewModel = new ViewModelProvider(this).get(BluetoothViewModel.class);
// 将BluetoothSocket存储在ViewModel中 viewModel.setBluetoothSocket(bluetoothSocket);
第3步:在控制活动中检索BluetoothSocket
现在,当您导航到需要使用BluetoothSocket的控制活动时,您可以简单地从BluetoothViewModel中检索它:
// 在您的控制活动中
BluetoothViewModel viewModel = new ViewModelProvider(this).get(BluetoothViewModel.class);
//从ViewModel中获取BluetoothSocket
BluetoothSocket bluetoothSocket = viewModel.getBluetoothSocket();
if (bluetoothSocket != null && bluetoothSocket.isConnected()) {
// Yay, you can use the BluetoothSocket here for sending and receiving data!
}其他{
// Uh-oh, handle the case where the socket is not available or not connected
}
就是这样! ViewModel 将负责在配置更改和活动生命周期事件中保留 BluetoothSocket。