当你打开应用程序时,它会询问是否给予用户访问联系人列表,如果用户点击“是”,主页就会打开--到目前为止我的代码还能正常工作;如果用户点击“否”,则会弹出一个窗口,用户会再次请求权限。
问题是弹出窗口确实弹出了,但我无法让它再次请求访问。
下面是我代码-(JetPack编写器,Kotlin)
var APP_ACTIVITY: Context? = null
private const val REQUEST_CODE_CONTACTS_PERMISSION = 1
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
APP_ACTIVITY = this
setContent {
MyApp {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
// Request read and write permission
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS), REQUEST_CODE_CONTACTS_PERMISSION)
} else {
// Permission has already been granted, go to home page
ContactNavigation()
}
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
REQUEST_CODE_CONTACTS_PERMISSION -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted, go to home page
setContent {
MyApp {
ContactNavigation()
}
}
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
// Request read and write contacts permission again - DOES NOT SHOW
// ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS), REQUEST_CODE_CONTACTS_PERMISSION)
}
}
}
}
}
1条答案
按热度按时间ogq8wdun1#
1、首先,我建议您使用以下权限库:
2、定义一个请求权限的方法,提供2个回调函数获取当前是否获得权限:
3、代码显示如下: