我正在我的Fragment中调用requestPermissions()
,这是该函数的片段实现(我没有调用activity.requestPermission()
)。我的上级活动和片段中都有onRequestPermissionsResult()
。从Fragment调用权限后,它会触发错误的onRequestPermissionsResult()
。为什么会发生
片段请求权限:
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return if (item?.itemId == R.id.createNewChat) {
if (activity.hasReadContactsPermission()) {
startActivity(Intent(activity, PhoneBookActivity::class.java))
} else {
requestPermissions(
arrayOf(Manifest.permission.READ_CONTACTS),
Constants.MY_PERMISSIONS_READ_CONTACT
)
}
true
} else {
super.onOptionsItemSelected(item)
}
}
片段onRequestPermissionsResult()
:
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
when (requestCode) {
Constants.MY_PERMISSIONS_READ_CONTACT -> {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
startActivity(Intent(activity, PhoneBookActivity::class.java))
}
}
}
}
活动onRequestPermissionsResult()
:
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
when (requestCode) {
Constants.MY_PERMISSIONS_MULTIPLE -> {
if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
startService(Intent(this, RegisterDeviceTokenTask::class.java))
if (smartServiceBound) {
smart113Service!!.onMainActivityStarted()
} else {
requestPermissionsUtil(
requiredPermissions,
Constants.MY_PERMISSIONS_MULTIPLE
)
}
}
}
}
}
我可能会在Activity中侦听此权限检查,但是当requestCode从Fragment移到Activity时,requestCode会发生变化,而我不想弄乱它。
在片段中触发onRequestPermissionResult()
的解决方案是什么?