我试着打电话给Kotlin,就像这样:
imgPhone.setOnClick {
val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "1122334455"))
startActivity(intent)
}
单击手机图像时,没有任何外观。原来调试器显示了这个:
java.lang.SecurityException:Permission Denial:启动Intent { act = android.intent.action.CALL dat = tel:xxxxxxxxxx cmp = com.android.server.telecom / .components.UserCallActivity}
我尝试了几种解决方案:
< uses-permission android:name =“android.permission.CALL_PHONE”/>
在呼叫意图为的活动中添加 android:exported =“true” 调用
< activity android:name=".activities.ProfileActivity" android:exported="true"/>
明确询问权限:
override fun onCreate() {
super.onCreate()
/*
more codes here
*/
setupPermissions()
}
fun setupPermissions() {
val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
if (permission != PackageManager.PERMISSION_GRANTED) {
Log.i("Error", "Permission to call denied")
}
}
到目前为止,这些解决方法都不起作用(在Android 6上)。仍然会发生相同的SecurityException。那么什么是正确的解决方案呢?
答案 0 :(得分:2)
在Marshmallow中,您必须在运行时请求权限,仅在清单中是不够的。在你写的选项(3)上你几乎做到了。在那里你只是在检查许可,但没有要求它。
官方文档是:https://developer.android.com/training/permissions/requesting
代码将与此类似:
fun checkPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CALL_PHONE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.CALL_PHONE),
42)
}
} else {
// Permission has already been granted
callPhone()
}
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
if (requestCode == 42) {
// If request is cancelled, the result arrays are empty.
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// permission was granted, yay!
callPhone()
} else {
// permission denied, boo! Disable the
// functionality
}
return
}
}
fun callPhone(){
val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "1122334455"))
startActivity(intent)
}
不要忘记你也需要它在清单上。 而且您可以删除从您的活动中导出的内容,这是毫无意义的。
我希望它有所帮助!