我有一个简单的空活动,用于检查是否需要请求权限。当调用registerForActivityResult
时,它会崩溃并出现错误java.lang.IllegalStateException: LifecycleOwner com.example.app.PermsRequester@41a30da is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.
。根据我的研究,我认为我需要检查savedInstanceState
是否为null
,如果是,则创建一个新的fragment
?我不确定这是否是正确的解决方案,也不确定如何实施。以下是代码:
class PermsRequester : AppCompatActivity() {
requestPerms = false
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_perms_requester)
findViewById<Button>(R.id.acceptButton).setOnClickListener { accepted() }
}
private fun accepted() {
//There is code here to check if rationale dialog needs to be displayed
//There is code here to build a mutable list of permissions that need to be requested and sets requestPerms = true
if(requestPerms)
requestPermissions()
}
private fun requestPermissions() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//app crashes on the following line
val requestMultiplePermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
permissions -> permissions.entries.forEach {
//Handles permission result
}
}
}
}
}
您需要在活动的onStart
之前registerForActivityResult
。
private lateinit var requestMultiplePermissionsLauncher:
ActivityResultLauncher<Array<String>>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestMultiplePermissionsLauncher =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
permissions.entries.forEach {
//Handles permission result
}
}
}
private fun accepted() {
if(requestPerms) {
val permissions = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.CAMERA)
requestMultiplePermissionsLauncher.launch(permissions)
}
}