Android 权限请求及权限设置页面跳转的工具类

在别人的基础上修改了一点点。集中了常见的几种权限请求和常见手机品牌的权限设置页面跳转。先记下来,以后用得上。
话不多说,上代码

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.codepig.common.activity.BaseActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 权限处理类
 */
public class PermissionCompat {
    private final static String TAG = PermissionCompat.class.getSimpleName();
    private static PermissionCompat instance;

    //自己的项目包名
    private String packageName="com.myapp";

    /**
     * 检测文件的权限
     */
    private static String[] PERMISSIONS_EXTERNAL_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    /**
     * 存储
     */
    public final static int REQUEST_EXTERNAL_STORAGE = 99;

    /**
     * 检测相机的
     */
    public static String[] PERMISSION_CAMERA = {
            Manifest.permission.CAMERA};

    /**
     * 相机请求
     */
    public final static int REQUEST_CAMERA = 98;//华为的requestCode不能大于128

    /**
     * 检测录音
     */
    public static String[] PERMISSION_RECODE = {
            Manifest.permission.RECORD_AUDIO};

    /**
     * 录音请求
     */
    public final static int REQUEST_RECODE = 96;

    /**
     * 检测图片选择的
     */
    public static String[] PERMISSION_GALLERY = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    public static String[] PERMISSION_FILE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    /**
     * 相册选择
     */
    public final static int REQUEST_GALLERY = 97;

    /**
     * 检测拨打电话权限
     */
    private static String[] PERMISSION_CALL_PHONE = {
            Manifest.permission.CALL_PHONE,
    };

    /**
     * 拨打电话请求
     */
    public final static int REQUEST_CALL_PHONE = 10096;

    /**
     * 设备状态
     */
    public final static int REQUEST_PHONE_STATE = 100;

    private final static String[] PERMISSIONS_PHONE_STATE = {Manifest.permission.READ_PHONE_STATE};

    /**
     * 获取手机通讯录
     */
    private final static int REQUEST_READ_CONTACTS = 101;

    private final static String[] PERMISSIONS_READ_CONTACTS = {Manifest.permission.READ_CONTACTS};

    /**
     * 定位权限
     */
    private static String[] PERMISSION_LOCATION = {Manifest.permission.ACCESS_COARSE_LOCATION};

    /**
     * 分享相关权限
     */
    String[] ABOUT_SHARE = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CALL_PHONE,Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE};

    private PermissionCompat() {
        //
    }

    public static PermissionCompat getInstance() {
        if (instance == null) {
            synchronized (PermissionCompat.class) {
                if (instance == null) {
                    instance = new PermissionCompat();
                }
            }
        }
        return instance;
    }

    public boolean checkCameraPermission(Activity activity) {
        return checkPermission(activity, PERMISSION_CAMERA, REQUEST_CAMERA);
    }

    public boolean checkRecodePermission(Activity activity) {
        return checkPermission(activity, PERMISSION_RECODE, REQUEST_RECODE);
    }

    /**
     * 检测文件读写
     */
    public boolean checkFilePermission(Activity activity) {
        return checkPermission(activity, PERMISSION_FILE, REQUEST_EXTERNAL_STORAGE);
    }

    /**
     * 检测相册
     */
    public boolean checkGalleryPermission(Activity activity) {
        return checkPermission(activity, PERMISSION_GALLERY, REQUEST_GALLERY);
    }

    /**
     * 检测电话
     */
    public boolean checkCallPhonePermission(Activity activity) {
        return checkPermission(activity, PERMISSION_CALL_PHONE, REQUEST_CALL_PHONE);
    }

    /**
     * 检测文件读写
     */
    public boolean checkStoragePermission(Activity activity) {
        return checkPermission(activity, PERMISSIONS_EXTERNAL_STORAGE, REQUEST_EXTERNAL_STORAGE);
    }

    /**
     * 检测手机状态权限
     * @param activity
     * @return
     */
    public boolean checkPhoneStatePermission(Activity activity) {
        return checkPermission(activity, PERMISSIONS_PHONE_STATE,REQUEST_PHONE_STATE);
    }

    /**
     * 检查手机通讯录权限
     * @param activity
     * @return
     */
    public boolean checkReadContactsPermission(Activity activity) {
        return checkPermission(activity, PERMISSIONS_READ_CONTACTS,REQUEST_READ_CONTACTS);
    }

    /**
     * 检测定位
     */
    public boolean checkLocationPermission(Activity activity) {
        return checkPermission(activity, PERMISSION_LOCATION, REQUEST_LOCATION);
    }

    /**
     * 定位权限
     */
    public final static int REQUEST_LOCATION = 10097;

    /**
     * 定位权限
     */
    public final static int REQUEST_SOCIAL_SHARE = 10098;

    /**
     * 分享相关权限
     * @param activity
     * @return
     */
    public boolean checkAboutSharePermission(Activity activity) {
        return checkPermission(activity, ABOUT_SHARE, REQUEST_SOCIAL_SHARE);
    }

    /**
     * @param activity
     * @param permission   需要检测的权限数组
     * @param request_code 请求的request code 自定义
     * @return
     */
    public boolean checkPermission(Activity activity, String[] permission, int request_code) {
        for (String str : permission) {
            int check = ContextCompat.checkSelfPermission(activity, str);
            boolean is_granted = (check == PackageManager.PERMISSION_GRANTED);
            if (!is_granted) { //
                BaseActivity baseActivity=(BaseActivity) activity;
                switch (request_code){
                    case REQUEST_RECODE:
                        baseActivity.showPermissionAlert("请在应用权限设置允许录音");
                        break;
                    case REQUEST_CAMERA:
                        baseActivity.showPermissionAlert("请在应用权限设置允许使用摄像头");
                        break;
                    case REQUEST_EXTERNAL_STORAGE:
                        baseActivity.showPermissionAlert("请在应用权限设置允许读写手机存储");
                        break;
                    case REQUEST_CALL_PHONE:
                        baseActivity.showPermissionAlert("请在应用权限设置允许拨打电话");
                        break;
                    case REQUEST_GALLERY:
                        baseActivity.showPermissionAlert("请在应用权限设置允许访问手机相册及摄像头");
                        break;
                }
                ActivityCompat.requestPermissions(
                        activity,
                        permission,
                        request_code
                );
                return false;
            }
        }
        return true;
    }


    /**
     * 跳转至权限设置页面
     * @param activity
     */
    public void goPermissionSet(Activity activity) {
        String name = Build.MANUFACTURER;
        switch (name) {
            case "HUAWEI":
                goHuaWeiManager(activity);
                break;
            case "vivo":
                goVivoManager(activity);
                break;
            case "OPPO":
                goOppoManager(activity);
                break;
            case "Coolpad":
                goCoolpadManager(activity);
                break;
            case "Meizu":
                goMeizuManager(activity);
                break;
            case "Xiaomi":
                goXiaoMiManager(activity);
                break;
            case "samsung":
                goSangXinManager(activity);
                break;
            case "Sony":
                goSonyManager(activity);
                break;
            case "LG":
                goLGManager(activity);
                break;
            default:
                goIntentSetting(activity);
                break;
        }
    }

    private void goLGManager(Activity activity){
        try {
            Intent intent = new Intent(packageName);
            ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings$AccessLockSummaryActivity");
            intent.setComponent(comp);
            activity.startActivity(intent);
        } catch (Exception e) {
            ToastUtil.showToast("跳转失败");
            e.printStackTrace();
            goIntentSetting(activity);
        }
    }
    private void goSonyManager(Activity activity){
        try {
            Intent intent = new Intent(packageName);
            ComponentName comp = new ComponentName("com.sonymobile.cta", "com.sonymobile.cta.SomcCTAMainActivity");
            intent.setComponent(comp);
            activity.startActivity(intent);
        } catch (Exception e) {
            ToastUtil.showToast("跳转失败");
            e.printStackTrace();
            goIntentSetting(activity);
        }
    }

    private void goHuaWeiManager(Activity activity) {
        try {
            Intent intent = new Intent(packageName);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
            intent.setComponent(comp);
            activity.startActivity(intent);
        } catch (Exception e) {
            ToastUtil.showToast("跳转失败");
            e.printStackTrace();
            goIntentSetting(activity);
        }
    }

    private static String getMiuiVersion(Activity activity) {
        String propName = "ro.miui.ui.version.name";
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(
                    new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return line;
    }

    private void goXiaoMiManager(Activity activity) {
        String rom = getMiuiVersion(activity);
        Intent intent=new Intent();
        if ("V6".equals(rom) || "V7".equals(rom)) {
            intent.setAction("miui.intent.action.APP_PERM_EDITOR");
            intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            intent.putExtra("extra_pkgname", packageName);
        } else if ("V8".equals(rom) || "V9".equals(rom)) {
            intent.setAction("miui.intent.action.APP_PERM_EDITOR");
            intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            intent.putExtra("extra_pkgname", packageName);
        } else {
            goIntentSetting(activity);
        }
    }

    private void goMeizuManager(Activity activity) {
        try {
            Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.putExtra("packageName", packageName);
            activity.startActivity(intent);
        } catch (ActivityNotFoundException localActivityNotFoundException) {
            localActivityNotFoundException.printStackTrace();
            goIntentSetting(activity);
        }
    }

    private void goSangXinManager(Activity activity) {
        //三星4.3可以直接跳转
        goIntentSetting(activity);
    }

    private void goIntentSetting(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        try {
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void goOppoManager(Activity activity) {
        doStartApplicationWithPackageName("com.coloros.safecenter",activity);
    }

    /**
     * doStartApplicationWithPackageName("com.yulong.android.security:remote")
     * 和Intent open = getPackageManager().getLaunchIntentForPackage("com.yulong.android.security:remote");
     * startActivity(open);
     */
    private void goCoolpadManager(Activity activity) {
        doStartApplicationWithPackageName("com.yulong.android.security:remote",activity);
      /*  Intent openQQ = getPackageManager().getLaunchIntentForPackage("com.yulong.android.security:remote");
        startActivity(openQQ);*/
    }

    private void goVivoManager(Activity activity) {
        doStartApplicationWithPackageName("com.bairenkeji.icaller",activity);
     /*   Intent openQQ = getPackageManager().getLaunchIntentForPackage("com.vivo.securedaemonservice");
        startActivity(openQQ);*/
    }

    private void doStartApplicationWithPackageName(String packagename,Activity activity) {
        // 通过包名获取此APP详细信息,包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = activity.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return;
        }
        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);
        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = activity.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);
        System.out.println("resolve info List" + resolveinfoList.size());
        for (int i = 0; i < resolveinfoList.size(); i++) {
            System.out.println("PermissionPageManager"+resolveinfoList.get(i).activityInfo.packageName + resolveinfoList.get(i).activityInfo.name);
        }
        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packageName参数2 = 参数 packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 该APP的LAUNCHER的Activity[组织形式:packageName参数2.mainActivityName]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            // 设置ComponentName参数1:packageName参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);
            intent.setComponent(cn);
            try {
                activity.startActivity(intent);
            } catch (Exception e) {
                goIntentSetting(activity);
                e.printStackTrace();
            }
        }
    }

}

使用:
判断及权限申请

PermissionCompat.getInstance().checkRecodePermission((Activity) context)

申请结果回调

/**
     * 权限申请回调
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
        boolean _permission=true;
        switch (requestCode){
            case REQUEST_RECODE:
            case REQUEST_CAMERA:
            case REQUEST_EXTERNAL_STORAGE:
            case REQUEST_CALL_PHONE:
            case REQUEST_GALLERY:
                for(int i=0;i<grantResults.length;i++){
                    if(grantResults[i]!=0){
                        _permission=false;
                    }
                }
                if(_permission){
                    if(permissionAlertDialog.isShowing()) {
                        hidePermissionAlert();
                    }
                }
                break;
        }
    }

跳转应用权限设置页面

PermissionCompat.getInstance().goPermissionSet(this);

关于跳转应用权限设置页面,小米手机上有个很坑爹的问题。在开发者模式下。用以上代码跳转的页面和从系统设置里进去的权限设置页面其实不是同一个。这导致了跳转后做的修改在系统设置的权限页面看不到变化。
而且如果在开发者模式下的启用MIUI优化是关闭的,那么系统的权限设置页面将是无效的。


相关github地址:
https://github.com/codeqian/MVVMDemo/blob/master/common/src/main/java/com/codepig/common/util/PermissionCompat.java

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