蓝牙通信app android studio例子
时间: 2023-05-19 19:03:55 浏览: 60
可以在Android Studio中使用BluetoothAdapter和BluetoothSocket类来实现蓝牙通信。以下是一个简单的例子:
1. 首先,在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
2. 在你的Activity中,声明以下变量:
private BluetoothAdapter mBluetoothAdapter;
private BluetoothSocket mBluetoothSocket;
private OutputStream mOutputStream;
3. 在onCreate()方法中初始化BluetoothAdapter:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// 设备不支持蓝牙
return;
}
4. 扫描并连接到蓝牙设备:
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("设备名称")) {
// 连接到设备
mBluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
mBluetoothSocket.connect();
mOutputStream = mBluetoothSocket.getOutputStream();
break;
}
}
5. 发送数据:
String message = "Hello, Bluetooth!";
mOutputStream.write(message.getBytes());
注意:以上代码仅为示例,实际使用时需要进行错误处理和异常处理。