Android 蓝牙发送字节数组:完整示例代码及使用教程
以下是一个通过蓝牙发送字节数组的示例代码,包含连接、发送、断开连接等操作。
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
public class BluetoothSender {
private BluetoothAdapter bluetoothAdapter;
private BluetoothSocket bluetoothSocket;
private OutputStream outputStream;
private BluetoothDevice bluetoothDevice;
public BluetoothSender(BluetoothAdapter adapter, BluetoothDevice device) {
bluetoothAdapter = adapter;
bluetoothDevice = device;
}
public boolean connect() {
try {
UUID uuid = UUID.fromString('00001101-0000-1000-8000-00805F9B34FB');
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
bluetoothSocket.connect();
outputStream = bluetoothSocket.getOutputStream();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void send(byte[] data) {
try {
outputStream.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
outputStream.close();
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用示例
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice('设备的MAC地址');
BluetoothSender bluetoothSender = new BluetoothSender(bluetoothAdapter, bluetoothDevice);
if (bluetoothSender.connect()) {
byte[] data = 'Hello, World!'.getBytes();
bluetoothSender.send(data);
bluetoothSender.disconnect();
}
注意
- 确保在使用该代码之前已经获取了蓝牙权限,并且已经配对了目标蓝牙设备。
- UUID ('00001101-0000-1000-8000-00805F9B34FB') 应根据实际情况修改,具体取决于目标设备的协议。
- 代码中使用了
'设备的MAC地址',请将其替换为实际的蓝牙设备的 MAC 地址。 - 此示例代码仅供参考,您可能需要根据实际需求进行调整。
更多内容
希望这篇文章对您有所帮助。如果您有任何问题,请随时留言。
原文地址: https://www.cveoy.top/t/topic/o0yC 著作权归作者所有。请勿转载和采集!