Android Bluetooth 权限请求:Java 与 Kotlin 代码对比
Android 蓝牙权限请求:Java 与 Kotlin 代码对比
本文将展示如何使用 Java 和 Kotlin 语言请求 Android 设备的蓝牙权限。
Java 代码
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivityForResult(intent, RESULT_OK);
Kotlin 代码
val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
return
}
startActivityForResult(intent, RESULT_OK)
代码分析:
-
创建 Intent:
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);使用BluetoothAdapter.ACTION_REQUEST_ENABLE常量创建一个 Intent 对象,用于启动蓝牙启用请求。 -
检查蓝牙连接权限:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { ... }使用ActivityCompat.checkSelfPermission()方法检查当前应用是否拥有BLUETOOTH_CONNECT权限。如果未获得权限,则直接返回。 -
启动蓝牙启用请求:
startActivityForResult(intent, RESULT_OK);使用startActivityForResult()方法启动蓝牙启用请求,并将请求结果返回到onActivityResult()方法中。
注意事项:
- 在 Android 6.0 (API 级别 23) 及更高版本中,需要使用
ActivityCompat.checkSelfPermission()方法检查权限。 - 在 AndroidManifest.xml 文件中声明
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />权限。
总结:
本文介绍了如何在 Android 中使用 Java 和 Kotlin 语言请求蓝牙权限。通过使用 ActivityCompat.checkSelfPermission() 检查权限,以及 Intent 启动蓝牙启用请求,可以方便地实现蓝牙功能。
原文地址: https://www.cveoy.top/t/topic/quxS 著作权归作者所有。请勿转载和采集!