本文介绍了被测READ_PHONE_STATE的Android M权限(危险权限)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试使用 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.这是出来了.

我声明许可为:

<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 方法来完成.

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 方法请求权限,例如

You can request the permission with the requestPermissions method, as such

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权限(危险权限)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 17:45