美文网首页Android大法好总结经验
封装Android M动态权限申请库

封装Android M动态权限申请库

作者: Ggx的代码之旅 | 来源:发表于2016-09-23 21:58 被阅读1233次

    这段时间,由于项目上适配android M 中的动态权限申请,频繁的写了一些重复的权限申请代码,都快想吐了,还有各种fragment中嵌套fragment的问题,既如此何不把它封装一下。下面直接看代码。

    public class MPermission {
        private static final int PERMISSION_CODE = 0x100;
        private Object obj;
        private static Method methodOK, methodFail;
        private String[] permissions;//权限数组
        private MPermission(Object obj) {
            this.obj=obj;
            methodOK=null;
            methodFail=null;
            findMethod(obj);
        }
        private void findMethod(Object o) {
            Method[] methods = o.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(PermissionOK.class)) {
                    methodOK = method;
                    if(methodFail!=null){
                        break;
                    }
                }else
     if(method.isAnnotationPresent(PermissionFail.class)){
                    methodFail=method;
                    if(methodOK!=null){
                        break;
                    }
                }
            }
        }
        public static MPermission with(Object obj) {
            return new MPermission(obj);
        }
        public MPermission setPermission(String... permissions) {
            if (permissions != null && permissions.length == 0) {
                throw new RuntimeException("必须填写需要申请的权限");
            }
            this.permissions = permissions;
            return this;
        }
        public void requestPermission() {
            int index=hasPermission(permissions);
            if (index!=-1) {
                //当检查时发现系统不存在这个权限的时候,需要判断当前系统版本是否>=23
                if(Build.VERSION.SDK_INT>=23){
                    requestPermissionApi23();
                }else{
                    //此处模仿官方API中的方法 进行回调
                    //API23一下的版本直接返回失败
                    int[] grantResults = new int[permissions.length];
                    for (int i = 0; i < grantResults.length; i++){
                        if(i<index){
                            grantResults[i] =PackageManager.PERMISSION_GRANTED;
                        }else {
                            grantResults[i]=PackageManager.PERMISSION_DENIED;
                        }
                    }
                    requestPermissionApi(grantResults);
                }
            } else {
                if(methodOK!=null) {
                    try {
                        methodOK.setAccessible(true);
                        methodOK.invoke(obj, new Object[]{});
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        @TargetApi(Build.VERSION_CODES.M)
        private void requestPermissionApi23(){
            if(obj instanceof Activity){         
                ((Activity)obj).requestPermissions(permissions,PERMISSION_CODE);
            }else if(obj instanceof Fragment){
                ((Fragment)obj).requestPermissions(permissions,PERMISSION_CODE);
            }
        }
        private void requestPermissionApi(int[] grantResults){
            if(obj instanceof ActivityCompat.OnRequestPermissionsResultCallback){
                ((ActivityCompat.OnRequestPermissionsResultCallback)obj).onRequestPermissionsResult(PERMISSION_CODE,permissions,grantResults);
            }else if(obj instanceof Fragment){
                ((Fragment)obj).onRequestPermissionsResult(PERMISSION_CODE,permissions,grantResults);
            }
        }
        private int hasPermission(String[] permissions) {
            int index=-1;
            for (int i=0,j=permissions.length;i<j;i++) {
                if (ActivityCompat.checkSelfPermission(Zilla.APP.getApplicationContext(), permissions[i])
                        != PackageManager.PERMISSION_GRANTED) {
                    index=i;
                    break;
                }
            }
            return index;
        }
        public static void onRequestPermissionsResult(Object o,int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            if (requestCode == PERMISSION_CODE) {
                if (grantResults.length == permissions.length) { 
                   for (int grant : grantResults) {
                        if (grant != PackageManager.PERMISSION_GRANTED) {
                            if(methodFail!=null){
                                try {
                                    methodFail.invoke(o,new Object[]{});
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                            return;
                        }
                    }
                    //权限都允许了,
                    if(methodOK!=null) {
                        try {
                            methodOK.setAccessible(true);
                            methodOK.invoke(o, new Object[]{});
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    if(methodFail!=null){
                        try {
                            methodFail.invoke(o,new Object[]{});
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    

    剩下的还有两个是注解类:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface PermissionFail {}
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface PermissionOK {}
    

    以上就是所以的源码,他的使用方式很简单

    在Fragment个Activity中你可以这样做

    //Call it anywhere you want it to.
    MPermission.with(this)
            .setPermission(Manifest.permission.READ_EXTERNAL_STORAGE
            ,Manifest.permission.WRITE_EXTERNAL_STORAGE...)
            .requestPermission();
                @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MPermission.onRequestPermissionsResult(this,requestCode,permissions,grantResults);
    }
    @PermissionOK
    private void valdateSuccess(){
        Log.i("权限通过");
    }
    @PermissionFail
    public void validateFail(){
        Log.i("没有相应的权限");
    }
    
    如此一劳永逸,是不是很简单
    
    欢迎共同探讨更多安卓,java,c/c++相关技术QQ群:392154157

    相关文章

      网友评论

      • sendy1211:hasPermission 方法里的
        private int hasPermission(String[] permissions) {
        int index=-1;
        for (int i=0,j=permissions.length;i<j;i++) {
        if (ActivityCompat.checkSelfPermission(Zilla.APP.getApplicationContext(), permissions[i])
        != PackageManager.PERMISSION_GRANTED) {
        index=i;
        break;
        }
        }
        return index;
        }
        Zilla.APP.getApplicationContext() 这个来自哪里?
        Ggx的代码之旅:@sendy1211 http://www.jianshu.com/p/1e96f96fb218
        Ggx的代码之旅:@sendy1211 我觉得 这篇文章就不要学了 后面我已经重新完成了一篇更好的

      本文标题:封装Android M动态权限申请库

      本文链接:https://www.haomeiwen.com/subject/rotxyttx.html