阅读量:86
Android中的Bluetooth通信可以通过多种方式实现,包括使用Android Bluetooth API或者第三方库。以下是一个简单的示例,展示如何使用Android Bluetooth API实现设备之间的通信:
-
确保设备支持蓝牙:首先,确保你的Android设备支持蓝牙,并且用户已经启用了蓝牙功能。
-
获取必要的权限:在AndroidManifest.xml文件中添加必要的权限和特性声明。
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.bluetooth" android:required="true" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
- 初始化蓝牙适配器:在你的Activity中初始化蓝牙适配器。
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// 设备不支持蓝牙
return;
}
- 发现设备:使用蓝牙适配器的
startDiscovery()方法来发现附近的蓝牙设备。
bluetoothAdapter.startDiscovery();
- 实现广播接收器:创建一个广播接收器来监听设备发现的结果。
private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 发现新设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 可以在这里进行设备的配对和连接
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(bluetoothReceiver, filter);
- 连接到设备:使用
BluetoothAdapter的getBond()方法来建立与设备的连接。
BluetoothDevice device = // 从发现列表中选择设备
BluetoothSocket socket = null;
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
// 连接成功,可以进行数据传输
} catch (IOException e) {
// 连接失败
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// 关闭连接失败
}
}
}
- 发送和接收数据:使用
BluetoothSocket的getInputStream()和getOutputStream()方法来发送和接收数据。
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
// 发送数据
byte[] sendData = "Hello, Bluetooth!".getBytes();
outputStream.write(sendData);
outputStream.flush();
// 接收数据
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
String receivedData = new String(buffer, 0, bytesRead);
- 关闭连接:在完成数据传输后,关闭输入输出流和蓝牙连接。
inputStream.close();
outputStream.close();
socket.close();
unregisterReceiver(bluetoothReceiver);
请注意,这只是一个基本的示例,实际应用中可能需要处理更多的细节,例如配对设备、处理连接失败的情况、管理多个设备连接等。此外,如果你需要更高级的功能,可以考虑使用第三方库,如Android Bluetooth LE Library (Android-BLE-Library) 或 GreenDAO。