Android 11开关蓝牙

在Android开发中,经常会涉及到控制设备的蓝牙功能。Android 11对蓝牙的管理做出了一些变化,本文将介绍如何在Android 11中开关蓝牙,并附带代码示例。

在Android 11中开关蓝牙

在Android 11中,开关蓝牙需要申请相应的权限,并使用新的API来实现。首先,我们需要在AndroidManifest.xml中添加权限声明:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

接下来,我们可以在Activity或Fragment中通过以下代码来开关蓝牙:

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
    // 设备不支持蓝牙
} else {
    if (bluetoothAdapter.isEnabled()) {
        bluetoothAdapter.disable(); // 关闭蓝牙
    } else {
        bluetoothAdapter.enable(); // 打开蓝牙
    }
}

示例代码

下面是一个简单的示例代码,演示了如何在Android 11中开关蓝牙:

public class MainActivity extends AppCompatActivity {

    private final int REQUEST_ENABLE_BT = 1;

    private BluetoothAdapter bluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            // 设备不支持蓝牙
            return;
        }

        // 请求蓝牙权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH},
                    REQUEST_ENABLE_BT);
        }

        // 开关蓝牙
        toggleBluetooth();
    }

    private void toggleBluetooth() {
        if (bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.disable();
        } else {
            bluetoothAdapter.enable();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_ENABLE_BT) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                toggleBluetooth();
            } else {
                // 未授予蓝牙权限
            }
        }
    }
}

结语

通过以上代码示例,我们可以在Android 11中轻松控制设备的蓝牙功能。在实际开发中,记得在使用蓝牙功能时要遵循相关的隐私政策和用户协议,保护用户的隐私信息。希望本文对你有所帮助,谢谢阅读!