从Android API Level 29开始,BluetoothAdapter.getDefaultAdapter()已被弃用。现在,应该使用BluetoothManager来获取BluetoothAdapter。
以下是一个简单的代码示例,展示如何使用BluetoothManager获取BluetoothAdapter:
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
请注意,在使用BluetoothAdapter之前,您必须确保用户已授予您的应用程序BLUETOOTH和BLUETOOTH_ADMIN权限。您可以在AndroidManifest.xml文件中添加以下权限:
除此之外,您可能还需要启用蓝牙。您可以在代码中使用以下代码行来实现:
bluetoothAdapter.enable();
这将打开系统蓝牙设置页面,让用户手动打开蓝牙。如果您想直接打开蓝牙,而不显示系统设置页面,那么您可以使用以下代码:
bluetoothAdapter.enable();
但请注意,这需要BLUETOOTH_ADMIN权限。