Android 蓝牙开发
一 配置环境
在 AndroidMainifest.xml 中配置下面的权限
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
## 有关于 定位权限的也需要加上
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
基础类
通过下面的方法 获取系统的 蓝牙适配器
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// 设备不支持蓝牙 -- 没得玩了..
System.out.println("设备不支持蓝牙");
return;
}
权限检测
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 权限未授予,请求权限
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_BLUETOOTH_SCAN_PERMISSION);
} else {
// 权限已授予,执行蓝牙扫描相关的操作
System.out.println("开启了蓝牙扫描");
bluetoothAdapter.startDiscovery();
}
异常情况处理
enableBtLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
// 在蓝牙已启用时执行的操作
System.out.println("在蓝牙已启用时执行的操作");
bluetoothAdapter.startDiscovery();
} else {
// 在蓝牙未启用时执行的操作
System.out.println("在蓝牙未启用时执行的操作");
/// 不开启蓝牙 -- 没得玩哦
}
});
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
enableBtLauncher.launch(enableBtIntent);
}
注册广播 接受蓝牙搜索结果
// 创建BroadcastReceiver以接收蓝牙设备的搜索结果
receiver = new BroadcastReceiver() {
@SuppressLint({"RestrictedApi", "MissingPermission"})
@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);
// 处理设备
System.out.println(device.getName());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getContext().registerReceiver(receiver, filter);
网友评论