|
手机与蓝牙通讯手机蓝牙「手机与蓝牙通讯」
发布时间:2025-01-23 浏览次数:2 返回列表
以下是Android平台上使用蓝牙通信的基本代码示例:
1. 首先,需要在AndroidManifest.xml文件中添加蓝牙相关的权限和特性:
```xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.bluetooth" />
```
2. 在Activity或Service中,需要获取BluetoothAdapter实例并进行初始化:
```java
private BluetoothAdapter mBluetoothAdapter;
...
// 获取BluetoothAdapter实例
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 启用蓝牙
if (mBluetoothAdapter == null) {
// 设备不支持蓝牙
} else {
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
}
```
3. 扫描其他蓝牙设备:
```java
// 开始扫描
mBluetoothAdapter.startDiscovery();
// 注册广播接收器,监听扫描结果
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
...
// 广播接收器,用于接收扫描结果
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 获取扫描结果
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device != null) {
// 处理扫描结果
}
}
}
};
```
4. 连接其他蓝牙设备:
```java
// 获取要连接的设备
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// 创建Socket并连接
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
// 获取输入输出流,进行数据传输
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
...
```
|