Android 获取联系人时 Marshmallow 安全异常
Android Marshmallow security exception when getting contacts
任何人都可以建议我应该对我的代码进行哪些更改以从 Android 中的联系人列表中检索联系人。我编写的逻辑对于棒棒糖及以下版本来说是完美的,但对于棒棒糖以上版本,它会崩溃并提示安全异常..
请参考https://developer.android.com/training/permissions/requesting.html
"Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app."
权限分为正常权限和危险权限。
以下代码检查应用程序是否有权读取用户的联系人,并在必要时请求权限:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation 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(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
任何人都可以建议我应该对我的代码进行哪些更改以从 Android 中的联系人列表中检索联系人。我编写的逻辑对于棒棒糖及以下版本来说是完美的,但对于棒棒糖以上版本,它会崩溃并提示安全异常..
请参考https://developer.android.com/training/permissions/requesting.html
"Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app."
权限分为正常权限和危险权限。
以下代码检查应用程序是否有权读取用户的联系人,并在必要时请求权限:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation 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(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}