在android中处理运行时权限的最佳方法

时间:2017-04-01 10:14:06

标签: android android-studio android-activity

我有一个目标sdk 21的旧项目,现在我必须提供运行时权限,所以任何人都可以建议我做任何最好和最简单的方法。

2 个答案:

答案 0 :(得分:2)

您可以在启动画面或第一屏幕上处理权限。

如果多次权限则一次处理。

如果用户拒绝任何权限,则会显示消息,需要一些权限。

希望它会对你有所帮助。

以下是如何处理多个权限的示例。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);


 if(checkAndRequestPermissions()){
     //all permission granted
 }else{
     //require all permission.
 }

}


private boolean checkAndRequestPermissions() {
    int camerapermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    int phonestate = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
    int location = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    int recordaudio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
    int permissionLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);


    List<String> listPermissionsNeeded = new ArrayList<>();

    if (camerapermission != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.CAMERA);
    }
    if (phonestate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
    }
    if (location != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
    }
    if (recordaudio != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.RECORD_AUDIO);
    }

    if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
        return false;
    }
    return true;
}



 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {

    switch (requestCode) {
        case REQUEST_ID_MULTIPLE_PERMISSIONS: {

            Map<String, Integer> perms = new HashMap<>();

            perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, 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.CAMERA) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        ) {
                    Log.d(TAG, "camera & location services permission granted");

                    // here you can do your logic all Permission Success Call
                        moveToNxtScreen();

                } else {
                    Log.d(TAG, "Some permissions are not granted ask again ");
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        showDialogOK("Some Permissions are required for Open Camera",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        switch (which) {
                                            case DialogInterface.BUTTON_POSITIVE:
                                                checkAndRequestPermissions();
                                                break;
                                            case DialogInterface.BUTTON_NEGATIVE:
                                                // proceed with logic by disabling the related features or quit the app.
                                                dialog.dismiss();
                                                break;
                                        }
                                    }
                                });
                    } else {
                        explain("You need to give some mandatory permissions to continue. Do you want to go to app settings?");
                    }
                }
            }
        }
    }

}

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

private void explain(String msg) {
    final android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(this);
    dialog.setMessage(msg)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    Utils.startInstalledAppDetailsActivity(LoginActivity.this);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    dialog.create().dismiss();
                    finish();
                }
            });
    dialog.show();
}

答案 1 :(得分:2)

创建两个变量,如

 private static final int REQUEST_CODE_PERMISSION = 1;
 String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

创建像这样的方法

之后
 private void getPermission() {
    if(Build.VERSION.SDK_INT>= 23) {

        if (checkSelfPermission(mPermission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{mPermission,
                    },
                    REQUEST_CODE_PERMISSION);
            return;
        }

        else
        {
            /* your code if permission already access 
        }
    }
}

覆盖onRequestPermissionsResult方法之后

 @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    Log.e("Req Code", "" + requestCode);
    if (requestCode == REQUEST_CODE_PERMISSION) {
        if (grantResults.length == 1 &&
                grantResults[0] == MockPackageManager.PERMISSION_GRANTED ) {
            methodRedirect();
        }
        else{
            this.getPermission();
        }
    }
}

这样即使用户拒绝许可,也会再次显示。

您可以像这样管理多个权限。