一文彻底解决Android动态权限申请(下)

一文彻底解决Android动态权限申请(下)

作者:Lyoun_JAP

下面是完整版代码MyPermissionsUtil,MainActivity:

MyPermissionsUtil:

package top.lyoun.myusb;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.provider.Settings;import android.support.v4.app.ActivityCompat;/***我自己的动态权限组,用于android6.0以上,并适配android8.0以上动态权限申请 */public class MyPermissionsUtil {    //以下都是需要动态申请的权限组//STORAGE存储卡文件读写权限组    public final static int requestCode_storage = 100;    public static String permissions_storage[] = new String[]{            "android.permission.WRITE_EXTERNAL_STORAGE",            "android.permission.READ_EXTERNAL_STORAGE"    };    //MICROPHONE麦克风权限组    public final static int requestCode_audio = 101;    public static String permissions_audio[] = new String[]{            "android.permission.RECORD_AUDIO"    };    //CAMERA相机权限组    public final static int requestCode_camera = 102;    public static String permissions_camera[] = new String[]{            "android.permission.CAMERA"    };    //LOCATION位置权限组    public final static int requestCode_location = 103;    public static String permissions_location[] = new String[]{            "android.permission.ACCESS_FINE_LOCATION",            "android.permission.ACCESS_COASE_LOCATION"    };    //PHONE手机权限组    public final static int requestCode_phone = 104;    public static String permissions_phone[] = new String[]{            "android.permission.READ_PHONE_STATE",            "android.permission.CALL_PHONE",            "android.permission.READ_CALL_LOG",            "android.permission.WRITE_CALL_LOG"    };    //CALENDAR日历权限组    public final static int requestCode_calendar = 105;    public static String permissions_calendar[] = new String[]{            "android.permission.READ_CALENDAR",            "android.permission.WRITE_CALENDAR"    };    //CONTACTS联系人权限组    public final static int requestCode_contacts = 106;    public static String permissions_contacts[] = new String[]{            "android.permission.READ_CONTACTS",            "android.permission.WRITE_CONTACTS",            "android.permission.GET_ACCOUNTS"    };    //SMS短信权限组    public final static int requestCode_sms = 107;    public static String permissions_sms[] = new String[]{            "android.permission.SEND_SMS",            "android.permission.RECEIVE_SMS",            "android.permission.READ_SMS",            "android.permission.RECEIVE_WAP_PUSH"    };    //BODY_SENSORS传感器权限组    public final static int requestCode_sensors = 108;    public static String permissions_sensors[] = new String[]{            "android.permission.BODY_SENSORS"    };    public final static int requestCode_all = 109;    public static int granted = PackageManager.PERMISSION_GRANTED;    private Activity mActivity;    private int mRequestCode;    //mustGrantedPermiss,必须要授予的权限,如果没有授予这些权限,则提示用户必须要授权后,app才能正常用    public static String[] mustGrantedPermiss = Splicing(permissions_storage, permissions_audio            , permissions_camera,            permissions_location,            permissions_phone,            permissions_calendar,            permissions_contacts,            permissions_sms,            permissions_sensors            );    public void checkPermissions(Activity activity, String[] needChecks, int requestCode) {        this.mActivity = activity;        this.mRequestCode = requestCode;        if (needChecks != null && needChecks.length > 0) {            //权限检查,只有android6.0及其以上才需要动态权限检查            if (android.os.Build.VERSION.SDK_INT > 22) {                for (int i = 0; i < needChecks.length; i++) {                    if (mActivity.checkSelfPermission(needChecks[i]) != granted) {                        System.out.println("您缺少" + needChecks[i] + "权限,需要动态添加权限");                        //requestCode请求码,表明当前是对哪个权限的请求                        ActivityCompat.requestPermissions(mActivity, needChecks, requestCode);                        break;                    }                }            }        }    }    boolean storagesGranted = false; //表明该权限是否已被授权    boolean audiosGranted = false;    boolean camerasGranted = false;    boolean locationsGranted = false;    boolean phonesGranted = false;    boolean calendarsGranted = false;    boolean contactsGranted = false;    boolean smsGranted = false;    boolean sensorsGranted = false;    String[] checkStorages = null; //表明客户端有没有请求授予该权限    String[] checkAudios = null;    String[] checkCameras = null;    String[] checkLocations = null;    String[] checkPhones = null;    String[] checkCalendars = null;    String[] checkContacts = null;    String[] checkSms = null;    String[] checkSensors = null;    int storagesDenyed = 0; //表明当前权限有没有被用户拒绝    int audiosDenyed = 0;    int camerasDenyed = 0;    int locationsDenyed = 0;    int phonesDenyed = 0;    int calendarsDenyed = 0;    int contactsDenyed = 0;    int smsDenyed = 0;    int sensorsDenyed = 0;    public static int compareCount = 0;    public static int needCompareCount = 0;    /**     * @param activity     * @param checkStorages  //存储卡文件读写权限组     * @param checkAudios    //麦克风录音权限     * @param checkCameras   //相机权限组     * @param checkLocations //位置权限组     * @param checkPhones    //手机权限组     * @param checkCalendars //日历权限组     * @param checkContacts  //联系人权限组     * @param checkSms       //短信权限组     * @param checkSensors   //传感器权限组     */    public void checkMorePermissions(Activity activity,                                     String[] checkStorages,                                     String[] checkAudios,                                     String[] checkCameras,                                     String[] checkLocations,                                     String[] checkPhones,                                     String[] checkCalendars,                                     String[] checkContacts,                                     String[] checkSms,                                     String[] checkSensors) {        this.mActivity = activity;        this.checkStorages = checkStorages;        this.checkAudios = checkAudios;        this.checkCameras = checkCameras;        this.checkLocations = checkLocations;        this.checkPhones = checkPhones;        this.checkCalendars = checkCalendars;        this.checkContacts = checkContacts;        this.checkSms = checkSms;        this.checkSensors = checkSensors;        //把数据初始化        storagesDenyed = 0;        audiosDenyed = 0;        camerasDenyed = 0;        locationsDenyed = 0;        phonesDenyed = 0;        calendarsDenyed = 0;        contactsDenyed = 0;        smsDenyed = 0;        sensorsDenyed = 0;        compareCount = 0;        needCompareCount = 0;        if(checkStorages != null && checkStorages.length > 0){            needCompareCount++;        }        if(checkAudios != null && checkAudios.length > 0){            needCompareCount++;        }        if(checkCameras != null && checkCameras.length > 0){            needCompareCount++;        }        if(checkLocations != null && checkLocations.length > 0){            needCompareCount++;        }        if(checkPhones != null && checkPhones.length > 0){            needCompareCount++;        }        if(checkCalendars != null && checkCalendars.length > 0){            needCompareCount++;        }        if(checkContacts != null && checkContacts.length > 0){            needCompareCount++;        }        if(checkSms != null && checkSms.length > 0){            needCompareCount++;        }        if(checkSensors != null && checkSensors.length > 0){            needCompareCount++;        }        //权限检查,只有android6.0及其以上才需要动态权限检查        if (android.os.Build.VERSION.SDK_INT > 22) {            try {                if (checkStorages != null && checkStorages.length > 0) {                    int i = 0;                    for (; i < checkStorages.length; i++) {                        if (mActivity.checkSelfPermission(checkStorages[i]) != granted) {                            System.out.println("您缺少" + checkStorages[i] + "权限,需要动态添加权限");                            //requestCode请求码,表明当前是对哪个权限的请求                            storagesGranted = false;                            //needCompareCount++;                            ActivityCompat.requestPermissions(mActivity, checkStorages, requestCode_storage);                            break;                        }                    }                    if (i == checkStorages.length) {                        storagesGranted = true;                        if(needCompareCount > 0){                            needCompareCount--;                        }                    }                }                if (checkAudios != null && checkAudios.length > 0 && checkStorages != null                        && (storagesGranted || !(checkStorages != null && checkStorages.length > 0))) {//                    int i = 0;                    for (; i < checkAudios.length; i++) {                        if (mActivity.checkSelfPermission(checkAudios[i]) != granted) {                            System.out.println("您缺少" + checkAudios[i] + "权限,需要动态添加权限");                            //requestCode请求码,表明当前是对哪个权限的请求                            audiosGranted = false;                            //needCompareCount++;                            ActivityCompat.requestPermissions(mActivity, checkAudios, requestCode_audio);                            break;                        }                    }                    if (i == checkAudios.length) {                        audiosGranted = true;                        if(needCompareCount > 0){                            needCompareCount--;                        }                    }                }                if (checkCameras != null && checkCameras.length > 0                        && (storagesGranted || !(checkStorages != null && checkStorages.length > 0))                        && (audiosGranted || !(checkAudios != null && checkAudios.length > 0))) {                    int i = 0;                    for (; i < checkCameras.length; i++) {                        if (mActivity.checkSelfPermission(checkCameras[i]) != granted) {                            System.out.println("您缺少" + checkCameras[i] + "权限,需要动态添加权限");                            //requestCode请求码,表明当前是对哪个权限的请求                            camerasGranted = false;                            //needCompareCount++;                            ActivityCompat.requestPermissions(mActivity, checkCameras, requestCode_camera);                            break;                        }                    }                    if (i == checkCameras.length) {                        camerasGranted = true;                        if(needCompareCount > 0){                            needCompareCount--;                        }                    }                }                if (checkLocations != null && checkLocations.length > 0 && !locationsGranted                        && (storagesGranted || !(checkStorages != null && checkStorages.length > 0))                        && (audiosGranted || !(checkAudios != null && checkAudios.length > 0))                        && (camerasGranted || !(checkCameras != null && checkCameras.length > 0))) {                    int i = 0;                    for (; i < checkLocations.length; i++) {                        System.out.println("location: " + i + " : "                        + checkLocations[i] + "," + mActivity.checkSelfPermission(checkLocations[i]));                        if (mActivity.checkSelfPermission(checkLocations[i]) == granted) {                            //requestCode请求码,表明当前是对哪个权限的请求                            locationsGranted = true;                            if(needCompareCount > 0){                                needCompareCount--;                            }                            break;                        }                    }                    if (i == checkLocations.length && !locationsGranted) {                        System.out.println("why location: " + i                                + "," + checkLocations.length + "," + locationsGranted);                        locationsGranted = false;                        //needCompareCount++;                        ActivityCompat.requestPermissions(mActivity, checkLocations, requestCode_location);                    }                }                if (checkPhones != null && checkPhones.length > 0 && !phonesGranted                        && (storagesGranted || !(checkStorages != null && checkStorages.length > 0))                        && (audiosGranted || !(checkAudios != null && checkAudios.length > 0))                        && (camerasGranted || !(checkCameras != null && checkCameras.length > 0))                        && (locationsGranted || !(checkLocations != null && checkLocations.length > 0))) {//                    int i = 0;                    for (; i < checkPhones.length; i++) {                        if (mActivity.checkSelfPermission(checkPhones[i]) != granted) {                            System.out.println("您缺少" + checkPhones[i] + "权限,需要动态添加权限");                            //requestCode请求码,表明当前是对哪个权限的请求                            phonesGranted = false;                            //needCompareCount++;                            ActivityCompat.requestPermissions(mActivity, checkPhones, requestCode_phone);                            break;                        }                    }                    if (i == checkPhones.length) {                        phonesGranted = true;                        if(needCompareCount > 0){                            needCompareCount--;                        }                    }                }                if (checkCalendars != null && checkCalendars.length > 0 && !calendarsGranted                        && (storagesGranted || !(checkStorages != null && checkStorages.length > 0))                        && (audiosGranted || !(checkAudios != null && checkAudios.length > 0))                        && (camerasGranted || !(checkCameras != null && checkCameras.length > 0))                        && (locationsGranted || !(checkLocations != null && checkLocations.length > 0))                        && (phonesGranted || !(checkPhones != null && checkPhones.length > 0))) {//&& (phonesGranted || !(checkPhones != null && checkPhones.length > 0))                    int i = 0;                    for (; i < checkCalendars.length; i++) {                        if (mActivity.checkSelfPermission(checkCalendars[i]) != granted) {                            System.out.println("您缺少" + checkCalendars[i] + "权限,需要动态添加权限");                            //requestCode请求码,表明当前是对哪个权限的请求                            calendarsGranted = false;                            //needCompareCount++;                            ActivityCompat.requestPermissions(mActivity, checkCalendars, requestCode_calendar);                            break;                        }                    }                    if (i == checkCalendars.length) {                        calendarsGranted = true;                        if(needCompareCount > 0){                            needCompareCount--;                        }                    }                }                if (checkContacts != null && checkContacts.length > 0 && !contactsGranted                        && (storagesGranted || !(checkStorages != null && checkStorages.length > 0))                        && (audiosGranted || !(checkAudios != null && checkAudios.length > 0))                        && (camerasGranted || !(checkCameras != null && checkCameras.length > 0))                        && (locationsGranted || !(checkLocations != null && checkLocations.length > 0))                        && (phonesGranted || !(checkPhones != null && checkPhones.length > 0))                        && (calendarsGranted || !(checkCalendars != null && checkCalendars.length > 0))) {//                    int i = 0;                    for (; i < checkContacts.length; i++) {                        if (mActivity.checkSelfPermission(checkContacts[i]) != granted) {                            System.out.println("您缺少" + checkContacts[i] + "权限,需要动态添加权限");                            //requestCode请求码,表明当前是对哪个权限的请求                            contactsGranted = false;                            //needCompareCount++;                            ActivityCompat.requestPermissions(mActivity, checkContacts, requestCode_contacts);                            break;                        }                    }                    if (i == checkContacts.length) {                        contactsGranted = true;                        if(needCompareCount > 0){                            needCompareCount--;                        }                    }                }                if (checkSms != null && checkSms.length > 0 && !smsGranted                        && (storagesGranted || !(checkStorages != null && checkStorages.length > 0))                        && (audiosGranted || !(checkAudios != null && checkAudios.length > 0))                        && (camerasGranted || !(checkCameras != null && checkCameras.length > 0))                        && (locationsGranted || !(checkLocations != null && checkLocations.length > 0))                        && (phonesGranted || !(checkPhones != null && checkPhones.length > 0))                        && (calendarsGranted || !(checkCalendars != null && checkCalendars.length > 0))                        && (contactsGranted || !(checkContacts != null && checkContacts.length > 0))) {//                    int i = 0;                    for (; i < checkSms.length; i++) {                        if (mActivity.checkSelfPermission(checkSms[i]) != granted) {                            System.out.println("您缺少" + checkSms[i] + "权限,需要动态添加权限");                            //requestCode请求码,表明当前是对哪个权限的请求                            smsGranted = false;                            //needCompareCount++;                            ActivityCompat.requestPermissions(mActivity, checkSms, requestCode_sms);                            break;                        }                    }                    if (i == checkSms.length) {                        smsGranted = true;                        if(needCompareCount > 0){                            needCompareCount--;                        }                    }                }                if (checkSensors != null && checkSensors.length > 0 && !sensorsGranted                        && (storagesGranted || !(checkStorages != null && checkStorages.length > 0))                        && (audiosGranted || !(checkAudios != null && checkAudios.length > 0))                        && (camerasGranted || !(checkCameras != null && checkCameras.length > 0))                        && (locationsGranted || !(checkLocations != null && checkLocations.length > 0))                        && (phonesGranted || !(checkPhones != null && checkPhones.length > 0))                        && (calendarsGranted || !(checkCalendars != null && checkCalendars.length > 0))                        && (contactsGranted || !(checkContacts != null && checkContacts.length > 0))                        && (smsGranted || !(checkSms != null && checkSms.length > 0))) {//                    int i = 0;                    for (; i < checkSensors.length; i++) {                        if (mActivity.checkSelfPermission(checkSensors[i]) != granted) {                            System.out.println("您缺少" + checkSensors[i] + "权限,需要动态添加权限");                            //requestCode请求码,表明当前是对哪个权限的请求                            sensorsGranted = false;                            //needCompareCount++;                            ActivityCompat.requestPermissions(mActivity, checkSensors, requestCode_sensors);                            break;                        }                    }                    if (i == checkSensors.length) {                        sensorsGranted = true;                        if(needCompareCount > 0){                            needCompareCount--;                        }                    }                }            } catch (Exception e) {                e.printStackTrace();            }        }    }    /***不再提示权限时的展示对话框     */    AlertDialog mPermissionDialog;    public void showSystemPermissionsSettingDialog(String tips) {        final String mPackName = mActivity.getPackageName();        if (mPermissionDialog == null) {            mPermissionDialog = new AlertDialog.Builder(mActivity)                    .setMessage(tips).setCancelable(false)                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {                        @Override                        public void onClick(DialogInterface dialog, int which) {                            cancelPermissionDialog();                            Uri packageURI = Uri.parse("package:" + mPackName);                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);                            mActivity.startActivity(intent);                            mActivity.finish();                        }                    })                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {                        @Override                        public void onClick(DialogInterface dialog, int which) {                            //关闭页面或者做其他操作                            cancelPermissionDialog();                        }                    })                    .create();        }        mPermissionDialog.show();    }    //关闭对话框    private void cancelPermissionDialog() {        if (mPermissionDialog != null) {            mPermissionDialog.cancel();            mPermissionDialog = null;            if(mActivity != null){                mActivity.finish();            }        }    }    //把两个数组拼接到一起    public static String[] Splicing(String[] checks1, String[] checks2) {        String[] checks = new String[0];        if (checks1 == null && checks2 == null) {            return null;        } else if (checks1 == null) {            checks = checks2;        } else if (checks2 == null) {            checks = checks1;        } else {            int len1 = checks1.length;            int len2 = checks2.length;            int len = len1 + len2;            checks = new String[len];            for (int i = 0; i < len; i++) {                if (i < len1) {                    checks[i] = checks1[i];                } else {                    checks[i] = checks2[i - len1];                }            }        }        return checks;    }    //把任意多个数组拼接到一起    public static String[] Splicing(String[] checks1, String[]... args) {        String[] checks = new String[0];        if (checks1 == null && args == null) {            return null;        } else if (args == null) {            checks = checks1;        } else {            if (checks1 != null) {                int len1 = checks1.length;                checks = new String[len1];                int j = 0;                for (; j < checks.length; j++) {                    checks[j] = checks1[j];                }            }            for (int i = 0; i < args.length; i++) {                String[] arg = args[i];                if (arg != null && arg.length > 0) {                    String[] temp = checks;                    checks = new String[checks.length + arg.length];                    for (int k = 0; k < checks.length; k++) {                        if (k < temp.length) {                            checks[k] = temp[k];                        } else {                            checks[k] = arg[k - temp.length];                        }                    }                }            }        }        return checks;    }    public static boolean getGranted(String[] permissions, int[] grantResults) {        boolean granted = false;        if (permissions != null && grantResults != null && permissions.length == grantResults.length) {            int i = 0;            for (; i < grantResults.length; i++) {                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {                    granted = false;                    break;                }            }            if (i == grantResults.length) {                granted = true;            }        }        return granted;    }}




在Android Q中引入了分区储存功能,在外部存储设备中为每个应用提供了一个“隔离存储沙盒”。其他应用无法直接访问应用的沙盒文件。由于文件是应用的私有文件,不再需要任何权限即可访问和保存自己的文件。此变更并有助于减少应用所需的权限数量,同时保证用户文件的隐私性。Android Q 更改了应用对设备外部存储设备中的文件(如:/sdcard )的访问方式。

继续使用READ_EXTERNAL_STORAGE和 WRITE_EXTERNAL_STORAGE 权限,只不过当拥有这些权限的时候,你只能访问媒体文件,无法访问其他文件。如果Target SDK > 28,请在manifest中添加android:requestLegacyExternalStorage=“true”

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,772评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,458评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,610评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,640评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,657评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,590评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,962评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,631评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,870评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,611评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,704评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,386评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,969评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,944评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,179评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,742评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,440评论 2 342