如何将BluetoothSocket从一个活动传输到另一个活动?

问题描述 投票:0回答:1

在我的 Android 应用程序中,我设置了两个活动:

  1. 连接活动:此活动有助于查找并连接 蓝牙设备。它显示了配对和可发现的列表 设备。
  2. 控制活动:连接后,我想使用此活动 使用蓝牙设备发送和接收数据。

我面临的问题是如何从连接活动到控制活动获取已建立的连接(由BluetoothSocket对象表示)。我考虑过使用应用程序类,但我不确定这是否是最好的方法。

有没有办法使用应用程序类来实现这种通信,或者推荐的方法是什么?

java android kotlin android-bluetooth android-developer-api
1个回答
0
投票

所以,首先,让我们创建一个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。

© www.soinside.com 2019 - 2024. All rights reserved.