簡體   English   中英

在“啟動畫面”上拒絕權限,但再次要求在另一活動中提示允許權限

[英]Deny permission on Splash screen but again ask for allow permission prompt in another activity

if (Build.VERSION.SDK_INT >= 23) {
    if (checkPermission()) {
        Log.e("permission", "Permission already granted.");
    } else {
        requestPermission();
    }
}

private boolean checkPermission() {
    int result = ContextCompat.checkSelfPermission(SolutionBrouchereActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (result == PackageManager.PERMISSION_GRANTED) {
        viewOrDownloadPDF();
        return true;
    } else {
        return false;
    }
}

private void requestPermission() {
    ActivityCompat.requestPermissions(getParent(), new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
}

拒絕初始屏幕上的權限並且無法在另一個活動中打開權限提示對話框后,此功能不起作用。

如果用戶未在初始屏幕上授予權限 ,則可以在新的Activity調用shouldShowRequestPermissionRationale方法。

參考: https : //developer.android.com/training/permissions/requesting

如果target SDK version is >=23則需要在運行時請求權限。 否則,Android將不會像舊版Android一樣請求許可。

如果是這種情況,那么如果轉到Settings > Apps > "Your app" > Permissions ,您應該能夠看到未授予任何Settings > Apps > "Your app" > Permissions

如果您不想詢問權限,可以將目標sdk版本降低到22,以獲取舊的權限系統。 不過,您仍然可以使用sdk 23版進行編譯。

因此對於> = 23,請使用以下代碼:

此代碼將自動檢測應顯示哪個對話框,因為android中顯示該權限對話框有特定限制。 如果嘗試了特定次數,則不會顯示權限對話框,我們將不得不自行將用戶移至其設置。

此代碼將幫助您實現兩種情況:

CustomPermissionManager.java:

public class CustomPermissionManager {
    public static final int STORAGE_PERMISSION = 8;
    public HashMap<Integer, ArrayList<PermissionManagerUtil.OnPermissionInterface>> onPermissionInterfaces = new HashMap<>();
    public HashMap<Integer, Boolean> hasAlreadyAskedPermission = new HashMap<>();
    private MainActivity context;

    public void init(MainActivity context) {
        this.context = context;
    }

    private boolean isAskedForFirstTime(String permissionName) {
        if (!PreferenceManager.getDefaultSharedPreferences(context).getBoolean(permissionName, false)) {
            PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(permissionName, true).commit();
            return true;
        }
        return false;
    }


    public void requestStoragePermission(Activity activity, boolean showAlertForSettingsIfNeeded, PermissionManagerUtil.OnPermissionInterface onPermissionInterface) {
        if (PermissionManagerUtil.instance.checkStoragePermission()) {
            onPermissionInterface.onPermissionGranted();
            return;
        }
        boolean isAskedFirstTime = isAskedForFirstTime(Manifest.permission.READ_EXTERNAL_STORAGE);

        if (showAlertForSettingsIfNeeded && !isAskedFirstTime && !ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            // if user clicked on "never ask again" then popup will not show by android
            //https://stackoverflow.com/questions/33224432/android-m-anyway-to-know-if-a-user-has-chosen-never-to-show-the-grant-permissi
            showAlertDialogWithAppSettings(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
        } else {

            if (onPermissionInterfaces.get(STORAGE_PERMISSION) == null) {
                onPermissionInterfaces.put(STORAGE_PERMISSION, new ArrayList<>());
            }
            if (onPermissionInterface != null) {
                onPermissionInterfaces.get(STORAGE_PERMISSION).add(onPermissionInterface);
            }
            if (!hasAlreadyAskedPermission.containsKey(STORAGE_PERMISSION)) {
                hasAlreadyAskedPermission.put(STORAGE_PERMISSION, true);
                ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION);
            }
        }
    }

    private void callPermissionManagerCallBack(int requestCode, int[] grantResults) {
        if (onPermissionInterfaces.containsKey(requestCode) && onPermissionInterfaces.get(requestCode) != null) {
            for (PermissionManagerUtil.OnPermissionInterface onPermissionInterface : onPermissionInterfaces.get(requestCode)) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onPermissionInterface.onPermissionGranted();
                } else {
                    onPermissionInterface.onPermissionNotGranted();
                }
            }
            hasAlreadyAskedPermission.remove(requestCode);
            onPermissionInterfaces.get(requestCode).clear();
        }

    }


    private void showAlertDialogWithAppSettings(String permission) {
        showAlertDialogWithAppSettings(context, permission);
    }

    @SuppressLint("RestrictedApi")
    private void showAlertDialogWithAppSettings(Activity context, String permission) {

        String title = "Allow permissions";
        String message = "Please allow this permission to enable this feature.";
        switch (permission) {
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                title = "Allow Storage Permission";
                message = "Please allow permission to do.... task";
                break;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        builder.setTitle(title);

        builder.setMessage(message);
        builder.setPositiveButton("Go to settings", (dialog, which) -> {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromParts("package", context.getPackageName(), null);
            intent.setData(uri);
            context.startActivity(intent);
        });
        builder.setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss());
        builder.show();
    }


    public boolean checkStoragePermission() {
        int resultExternalStorage = PermissionChecker.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        return resultExternalStorage == PackageManager.PERMISSION_GRANTED;
    }
}

這樣稱呼它:

    CustomPermissionManager customPermissionManager = new CustomPermissionManager();
    customPermissionManager.init(context);
    customPermissionManager.requestCameraPermission(true, new OnPermissionInterface() {
        @Override
        public void onPermissionGranted() {

            //permission granted
    viewOrDownloadPDF();

        }

        @Override
        public void onPermissionNotGranted() {

            // permission not granted
        }


    });

// To check permission is given or not
        boolean isGranted =  customPermissionManager.checkStoragePermission();

您將來也可以添加其他權限,例如通過添加相同類型的方法來添加STORAGE_PERMISSION。

將此功能放在通用文件中,並在每次使用時調用都會再次檢查

public static boolean checkPermission(final Activity context)
    {
        int currentAPIVersion = Build.VERSION.SDK_INT;
        if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
        {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED||ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //||ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED
                if (ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.READ_EXTERNAL_STORAGE)||ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)||ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.CALL_PHONE)) {
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                    alertBuilder.setCancelable(true);
                    alertBuilder.setTitle("Permission necessary");
                    alertBuilder.setMessage("External storage permission is necessary");
                    alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                        }
                    });
                    AlertDialog alert = alertBuilder.create();
                    alert.show();
                } else {
                    ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM