android - 在 Android M 中读取手机状态运行时错误

标签 android user-permissions

我已在 list 和 Activity 中授予读取手机状态的权限。但我仍然面临运行时异常。 在 fragment 中,我使用电话管理器获取 IMEI,在 Activity 中我已授予运行时权限。

这是我的错误:

java.lang.SecurityException: getImei: Neither user 10122 nor current process has android.permission.READ_PHONE_STATE.
                                                                            at android.os.Parcel.readException(Parcel.java:1620)
                                                                            at android.os.Parcel.readException(Parcel.java:1573)
                                                                            at com.android.internal.telephony.IPhoneSubInfo$Stub$Proxy.getImeiForSubscriber(IPhoneSubInfo.java:532)
                                                                            at android.telephony.TelephonyManager.getImei(TelephonyManager.java:783)
                                                                            at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:722)
                                                                            at com.sixmod.HomeFragment.sendTokenToServer(HomeFragment.java:3045)
                                                                            at com.sixmod.HomeFragment.onCreateView(HomeFragment.java:343)

Activity 代码在这里:

private  boolean checkAndRequestPermissions() {
        int permissionSendMessage = ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_PHONE_STATE);
        int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);

        List<String> listPermissionsNeeded = new ArrayList<>();
        if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (locationPermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }

在 onRequest 权限中,我已经这样检查了:

@Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        Log.d("TAG", "Permission callback called-------");
        switch (requestCode) {
            case REQUEST_ID_MULTIPLE_PERMISSIONS: {

                Map<String, Integer> perms = new HashMap<>();
                // Initialize the map with both permissions
                perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
                // Fill with actual results from user
                if (grantResults.length > 0) {
                    for (int i = 0; i < permissions.length; i++)
                        perms.put(permissions[i], grantResults[i]);
                    // Check for both permissions
                    if (perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
                    && perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        Log.d("TAG", "sms & location services permission granted");
                        // process the normal flow
                        //else any one or both the permissions are not granted
                    } else {
                        Log.d("TAG", "Some permissions are not granted ask again ");
                        //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
//                        // shouldShowRequestPermissionRationale will return true
                        //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                            showDialogOK("Read Phone State and Location Services Permission required for this app",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            switch (which) {
                                                case DialogInterface.BUTTON_POSITIVE:
                                                    checkAndRequestPermissions();
                                                    break;
                                                case DialogInterface.BUTTON_NEGATIVE:
                                                    android.os.Process.killProcess(android.os.Process.myPid());
                                                    System.exit(1);
                                                    // proceed with logic by disabling the related features or quit the app.
                                                    break;
                                            }
                                        }
                                    });
                        }
                        //permission is denied (and never ask again is  checked)
                        //shouldShowRequestPermissionRationale will return false
                        else {
                            Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
                                    .show();
                            //                            //proceed with logic by disabling the related features or quit the app.
                        }
                    }
                }
            }
        }

    }

    private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", okListener)
                .create()
                .show();
    }

最佳答案

在AndroidManifest.xml文件中添加

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

请求许可。

 int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
        } else {
            //TODO
        }

请求权限时处理回调。

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_READ_PHONE_STATE:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                //TODO
            }
            break;

        default:
            break;
    }
}

对于某些权限,您必须在运行时明确询问用户: http://developer.android.com/training/permissions/requesting.html

关于android - 在 Android M 中读取手机状态运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42688135/

相关文章:

Android Wifi Direct : Avoiding user acceptance when connecting to a known peer

Kubernetes、安全上下文、fsGroup 字段和运行容器的默认用户组 ID

spring - Grails 检查特定 Controller 操作的角色访问权限

android - 如何自定义 Swipe Refresh layout top Progress Bar or Loader?

android - android NSD onResolveFailed() 的错误代码意味着什么

android - 在android中接收和串联超过160个字符的短信

php - WebsitePanel - mysql_connect() : Access denied for user 'user' @'localhost' (using password: YES) on line 38. 连接到 mysql 时出错

ios - 如何防止 iOS 应用在更改相机权限后重置?

java - 使用 android 的默认图库 Intent

java - android app Toolbar.setTitle error Attempt to invoke virtual method 'void.androidx.appcompat.widget' 错误