在AndroidManifest.xml文件中添加以下代码:
在启用蓝牙之前,检查蓝牙是否已经启用,并使用以下代码:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter == null) {
// 设备不支持蓝牙
} else {
if(!bluetoothAdapter.isEnabled()) {
// 请求打开蓝牙
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}
使用以下代码监听蓝牙连接和断开:
public class BluetoothReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// 蓝牙设备已连接
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
// 蓝牙设备已断开
}
}
}
使用以下代码连接蓝牙设备:
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
其中,address为蓝牙设备的地址,MY_UUID为自定义的UUID。