android studio蓝牙连接代码
时间: 2023-07-07 14:35:56 浏览: 108
以下是一个简单的 Android Studio 蓝牙连接代码示例:
1. 首先需要声明权限
```xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
```
2. 在 onCreate 方法中获取 BluetoothAdapter 实例并启用蓝牙
```java
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// 设备不支持蓝牙
} else {
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
```
3. 在 onActivityResult 方法中处理启用蓝牙的结果
```java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK) {
// 蓝牙已启用
} else {
// 用户拒绝启用蓝牙
}
}
}
```
4. 扫描可用的蓝牙设备
```java
private void scanForDevices() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
}
private final BroadcastReceiver receiver = 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);
// 处理扫描到的设备
}
}
};
```
5. 连接蓝牙设备
```java
private void connectToDevice(BluetoothDevice device) {
BluetoothSocket socket = null;
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
// 连接成功,处理数据传输
} catch (IOException e) {
// 连接失败
}
}
```
以上是一个简单的蓝牙连接代码示例,具体实现还需要根据具体情况进行调整。
阅读全文