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

5cg8jx4n  于 2023-03-16  发布在  Android
关注(0)|答案(3)|浏览(142)

我有一个老项目的目标sdk21,现在我必须把运行时的权限,所以任何人都可以建议我任何最好的和简单的方法来做到这一点。

ct2axkht

ct2axkht1#

创建两个变量,如

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();
        }
    }
}

这样,即使用户拒绝权限,它也会再次显示。
可以像这样管理多个权限。

bsxbgnwa

bsxbgnwa2#

您可以处理启动画面或第一个画面上的权限。
如果有多个权限,则一次处理所有权限。
如果用户拒绝任何权限,则显示消息Some Permission Required。
希望对你有帮助。
以下是如何处理多个权限示例。

@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();
}
nqwrtyyt

nqwrtyyt3#

从Android SDK版本23开始,我们需要处理运行时权限,以便出于隐私目的访问一些受保护的功能或模块。

让我们开始了解在Android中处理运行时权限的最佳方法。

1.在清单文件中声明权限:
首先,在Manifest文件中,我们应该声明应用所需的权限。例如,如果一个应用想使用摄像头,它必须在其manifest文件中声明“android.permission.CAMERA”权限。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   package="com.test">

   <uses-permission android:name="android.permission.CAMERA" />
   <!--    Some other code-->
</manifest>

1.正在检查应用程序中的权限:
在Manifest文件中声明权限后,我们可以在应用代码中检查该权限。

ContextCompat.checkSelfPermission(
   context,
   permission
)

如果你想了解更多关于android应用程序运行时权限的处理,请查看**here**。

相关问题