测试READ_PHONE_STATE的Android M权限(危险权限) [英] Android M permission of the tested READ_PHONE_STATE(dangerous permissions)
问题描述
如果设备在使用 getLine1Number()尝试获取电话号码时运行Android 6.0或更高版本:
If the device is running Android 6.0 or higher when im trying to get phone number using getLine1Number():
java .lang.SecurityException:需要READ_PHONE_STATE:用户10184和当前进程都没有android.permission.READ_PHONE_STATE。
即将发布。
java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10184 nor current process has android.permission.READ_PHONE_STATE. This is coming out.
I声明权限为:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
推荐答案
在Android 6.0中,您需要明确询问用户授予权限。只是在清单中声明它是不够的。
In Android 6.0, you need to explicitly ask the user to grant the permissions. Just declaring it in the manifest isn't enough.
This article in the docs is a great place to start learning the new model, but I'll give a brief summary.
每次执行动作时这需要危险许可,您需要检查当前是否授予了权限,因为用户可以随时撤销该权限。
Every time you perform an action that requires a "dangerous permission," you need to check if the permission is currently granted, because the user can revoke it at any time.
这可以通过 checkSelfPermission
method。
This can be done with the checkSelfPermission
method.
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// We do not have this permission. Let's ask the user
}
您可以使用 requestPermissions
方法,因此
ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_READ_STATE);
其中 PERMISSION_READ_STATE
是一个由你稍后会检查回调方法。
Where PERMISSION_READ_STATE
is a constant integer defined by you to check in the callback method later.
然后你将在你的活动中覆盖 onRequestPermissionsResult
并查看是否有权限被授予。如果是,您可以继续执行危险操作。
You will then override onRequestPermissionsResult
in your activity and see if the permission was granted. If it was, you can go ahead and preform the dangerous action.
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_READ_STATE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted!
// you may now do the action that requires this permission
} else {
// permission denied
}
return;
}
}
}
这篇关于测试READ_PHONE_STATE的Android M权限(危险权限)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!