我这两天用的sdk为31的,然后获取蓝牙适配器,getDefaultAdapter()这个方法没法用,为啥sdk高了之后这个就过时了?除了降低版本,还有啥能获取蓝牙适配器?
该回答引用chatgpt:
在Android 10之前,可以使用 BluetoothAdapter.getDefaultAdapter() 来获取默认的蓝牙适配器。但是,从Android 10开始,该方法被标记为过时,原因是在Android 10中,应用程序需要启用位置权限才能访问蓝牙适配器。
取而代之的是,开发者可以通过调用 BluetoothManager 的 getAdapter() 方法来获取蓝牙适配器。BluetoothManager 可以通过 Context.getSystemService(Context.BLUETOOTH_SERVICE) 方法获取。下面是获取蓝牙适配器的示例代码:
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
需要注意的是,如果设备不支持蓝牙,getAdapter() 方法将返回 null。
在使用新的方法获取蓝牙适配器之前,还需要在应用程序的 AndroidManifest.xml 文件中添加以下权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
其中, android.permission.ACCESS_FINE_LOCATION 权限是必需的,因为在 Android 10 中,蓝牙扫描和连接需要该权限。
值得注意的是,如果你的应用程序只需要在 Android 10 及更高版本上运行,那么必须使用新的方法获取蓝牙适配器,否则应用程序将无法访问蓝牙适配器。如果你的应用程序需要支持旧版本的 Android,那么可以通过以下方式来处理:
BluetoothAdapter bluetoothAdapter;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
} else {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
这样,如果设备运行的是 Android 10 或更高版本,就会使用新的方法获取蓝牙适配器,否则将使用旧的方法获取。
if(Build.VERSION.SDK_INT >= 31) {
bluetoothAdapter = BluetoothAdapter.getAdapter();
}else{
bluetoothManager = BluetoothManager.getDefaultAdapter();
}