我正在按照Android文档示例实现权限时,它建议使用androidx
的RequestPermission
和requestPermissionLauncher
API来:
允许系统管理与权限请求相关联的请求代码
我基本上复制了示例代码:
private fun checkForPermissions() {
// setup permission callback
val requestPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
// success
Log.d("RPMT", "success")
} else {
Log.d("RPMT", "failure")
// failure
}
}
// check permission
if (ContextCompat.checkSelfPermission(
this@MainActivity,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
) {
Log.d("RPMT", "carry on with flow")
} else {
requestPermissionLauncher.launch(
Manifest.permission.CAMERA
)
}
}
然而,运行此代码后,我收到了一个
java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
该行出现错误
requestPermissionLauncher.launch(
堆栈跟踪:
java.lang.RuntimeException: Unable to start activity ComponentInfo{no.dwb.rpmt_kotlin_0/no.dwb.rpmt_kotlin_0.MainActivity}: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3122)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3261)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1977)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6923)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)
...
Caused by: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
at androidx.fragment.app.FragmentActivity.checkForValidRequestCode(FragmentActivity.java:715)
at androidx.fragment.app.FragmentActivity.validateRequestPermissionsRequestCode(FragmentActivity.java:730)
at androidx.core.app.ActivityCompat.requestPermissions(ActivityCompat.java:500)
at androidx.activity.ComponentActivity$2.onLaunch(ComponentActivity.java:192)
at androidx.activity.result.ActivityResultRegistry$3.launch(ActivityResultRegistry.java:160)
at androidx.activity.result.ActivityResultLauncher.launch(ActivityResultLauncher.java:42)
at no.dwb.rpmt_kotlin_0.MainActivity.checkForPermissions(MainActivity.kt:40)
at no.dwb.rpmt_kotlin_0.MainActivity.onCreate(MainActivity.kt:16)
我真的搞不明白这个问题。我已经添加了androidx gradle依赖。