在同一活动中从两个不同的功能请求WRITE_EXTERNAL_STORAGE权限

时间:2019-01-09 03:47:04

标签: android android-permissions android-6.0-marshmallow runtime-permissions

我对takeScreenshot和saveAsPDF有两个不同的功能,它们都需要WRITE_EXTERNAL_STORAGE权限。但是,如何在onRequestPermissionsResult中为同一活动中的相同权限创建切换用例,因为requestCode在两种情况下都是相同的。

1 个答案:

答案 0 :(得分:1)

您可以创建以下类似的单独类来检查并询问权限->

public class PermissionCheck {

    private static final String TAG = PermissionCheck.class.getSimpleName();

    private Context context;
    private static final int EXTERNAL_WRITE_PERMISSION_CODE = 620;
    private static final int CAMERA_PERMISSION_CODE = 335;

    public PermissionCheck(Context context) {
        this.context = context;
    }

    //  Check Required Permissions...
    public boolean CheckRequestedPermission(Context context, String CheckRequiredPermission) {
        return ContextCompat.checkSelfPermission(context, CheckRequiredPermission) == PackageManager.PERMISSION_GRANTED;
    }

    //  To Request Permission...
    private void requestPermission(final Context context, final String RequestedPermission, final int PermissionCode) {
        if (!CheckRequestedPermission(context, RequestedPermission)) {
            ActivityCompat.requestPermissions((Activity) context, new String[]{RequestedPermission}, PermissionCode);
        }
    }


    //  Just add Permission Code that you required to get permissions and call this method...
    public void AskPermission(int RequestCode) {
        switch (RequestCode) {
            case EXTERNAL_WRITE_PERMISSION_CODE:
                requestPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE, EXTERNAL_WRITE_PERMISSION_CODE);
                break;
            case CAMERA_PERMISSION_CODE:
                requestPermission(context, Manifest.permission.CAMERA, CAMERA_PERMISSION_CODE);
                break;
        }
    }
}

询问您想要的任何权限,并在Activity或片段中实现OnRequestPermissionResult,如下所示。

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case EXTERNAL_WRITE_PERMISSION_CODE:
                Log.d(TAG, "onPermissionResult : Permission Granted? " + IsExternalWritePermissionGranted);
                //  changing value based on permission Deny/Accept
                IsExternalWritePermissionGranted = permissionCheck.CheckRequestedPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            case CAMERA_PERMISSION:
                //  changing value based on permission Deny/Accept
                IsCameraPermissionGranted = permissionCheck.CheckRequestedPermission(this, Manifest.permission.CAMERA);
                break;
        }
    }

请注意,您从活动/片段传递给PermissionCheck的权限代码应该与PermissionCheck类中的相同。