美文网首页
Android M 运行时权限“快速”适配

Android M 运行时权限“快速”适配

作者: 野生大P | 来源:发表于2016-06-15 18:24 被阅读355次

    Android M是Google在15年中旬发布的新版本,相信开发者都不陌生了,Android 6.0其实就是多了个省电安全(运行时权限)嘛
    为什么现在还拿运行时权限出来老生常谈一下呢,因为针对Android M的运行时权限处理其实是小众需求,一般不关心手机内置的应用只要targetSDK在23以下就解决Android M运行时权限适配这个让开发人员无比蛋疼的问题了

    可是针对需要进行Android M运行时权限适配的应用来说你需要关心以下事情了


    1.直入主题

    • 这里就不写一堆运行时权限的介绍和官方API了,想了解的可以看我同事的相关文章:传送门
    • 当然市场上也有使用响应式编程的解决框架:RxPermissions

    所以本文针对的是不想用Rx编程,且想解决的更加简单更加符合用户完整体验的同学

    在做运行时权限适配的时候你一定会遇到以下问题
    • 1.现有代码怎么办?
    • 2.怎么简单解决?
    • 2.怎么不影响代码的可读性?
    • 3.没有权限的时候怎么办?/怎么容错,怎么不导致功能缺失

    那先来看下我认为的完整的运行时权限处理的流程图

    流程图-Android M运行时权限

    不是我故意复杂的,多一个无权限的引导是我认为的用户行为的闭环,一般我们就是提示一个SnackBar也不会干扰用户,当然你可以选择不用这一部分流程


    2.实现逻辑

    最先考虑怎么基于现有代码简单的不影响可读性的实现的时候,首先就想到了Action,如果你熟知RxAndroid响应式编程的话你一定比较熟悉,但是我这里将Action做成了一个类似责任链的方式

    Talk is cheap , Show me the code.

    • ***IAction ***
    public abstract class IAction {
        private IAction mParent;
    
        private IAction mChild;
    
        public IAction() {
        }
    
        final public boolean run() {
            if (mParent != null && mParent.run()) {
                return true;
            }
            return call();
        }
    
        /**
         * @return if return true interrupt
         */
        abstract public boolean call();
    
        public void onError() {
            if (getChild() != null) {
                getChild().onError();
            }
        }
    
        public IAction setParent(IAction parent) {
            this.mParent = parent;
            if (parent != null) {
                parent.setChild(this);
            }
            return this;
        }
    
        final public IAction getParent() {
            return mParent;
        }
    
        final protected void setChild(IAction child) {
            mChild = child;
        }
    
        final public IAction getChild() {
            return mChild;
        }
    
        public IAction getLastChild() {
            if (mChild == null) {
                return this;
            } else {
                return mChild.getLastChild();
            }
        }
    }
    

    这样设计的优势是便于封装现有代码,且单元性好能够很好能够任意组合(等会看到实现处你就会爱上它了)

    • IPermissionAction

    具体的运行时权限的逻辑处理类

    public abstract class IPermissionAction extends IAction implements InnerOnRequestPermissionsResult {
        private final int mRequestCode;
    
        private String mRequestPermission;
    
        private Activity mActivity;
    
        public boolean isNeedRequestPermission = true;
    
        public IPermissionAction(Activity activity) {
            mActivity = activity;
            mRequestPermission = getRequestPermission();
            if (TextUtils.isEmpty(mRequestPermission)) {
                mRequestCode = 0;
            } else {
                mRequestCode = Math.abs(mRequestPermission.hashCode());
            }
        }
    
        public abstract String getRequestPermission();
    
    
        public void isNeedRequestPermission(boolean isNeedRequestPermission) {
            this.isNeedRequestPermission = isNeedRequestPermission;
        }
    
        @Override
        final public boolean call() {
            if (mRequestCode == 0) {
                return false;
            }
            if (Build.VERSION.SDK_INT < 23) {
                return false;
            }
            int permissionCheck = ContextCompat.checkSelfPermission(mActivity, mRequestPermission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                //版本小于23  或者  有权限时
                return false;
            } else if (permissionCheck == PackageManager.PERMISSION_DENIED) {
                doRequestPermission();
                onPermissionUnable();
                return true;
            }
            return false;
        }
    
        @TargetApi(23)
        final private void doRequestPermission() {
            try {
                if (isNeedRequestPermission) {
                    LLog.e(mRequestPermission + " requestPermissions : " + mRequestCode);
                    mActivity.requestPermissions(new String[]{mRequestPermission}, mRequestCode);
                    RunTimePermissionManager.getInstance().addOnActivityPermissionsResults(this);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    
        @Override
        final public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            if (requestCode == mRequestCode) {
                RunTimePermissionManager.getInstance().removeOnActivityPermissionsResults(this);
    
                if (permissions != null && permissions.length > 0 && mRequestPermission.equals(permissions[0])) {
                    if (grantResults != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        LLog.e(permissions[0] + " permission allowed");
                        getLastChild().run();
                        return;
                    }
                }
    
                if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, mRequestPermission)) {
                    onPermissionDenied();
                } else {
                    onPermissionAlwaysDenied();
                }
            }
        }
    
        protected void onPermissionAlwaysDenied() {
            LLog.e(mRequestPermission + " onPermissionAlwaysDenied");
        }
    
        protected void onPermissionDenied() {
            LLog.e(mRequestPermission + " onPermissionDenied");
        }
    
        protected void onPermissionUnable() {
            LLog.e(mRequestPermission + " onPermissionUnable");
        }
    }
    
    • RunTimePermissionManager

    这个单例是为了接收和处理Activity的onRequestPermissionsResult的事件

    public class RunTimePermissionManager {
        private static RunTimePermissionManager mInstance;
    
        private ArrayList<InnerOnRequestPermissionsResult> mPermissionsResults = new ArrayList<>();
        private ArrayList<InnerOnRequestPermissionsResult> mRemovedPermissionsResults = new ArrayList<>();
    
        private RunTimePermissionManager() {
    
        }
    
        public static RunTimePermissionManager getInstance() {
            if (mInstance == null) {
                mInstance = new RunTimePermissionManager();
            }
            return mInstance;
        }
    
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            if (mPermissionsResults != null) {
                LLog.e("onRequestPermissionsResult : " + requestCode);
                for (int i = 0; i < mPermissionsResults.size(); i++) {
                    LLog.e("mPermissionsResults : " + i + " " + mPermissionsResults.get(i).toString());
                    InnerOnRequestPermissionsResult mPermissionsResult = mPermissionsResults.get(i);
                    if (mPermissionsResult != null) {
                        LLog.e("onRequestPermissionsResult goto: " + requestCode);
                        mPermissionsResult.onRequestPermissionsResult(requestCode, permissions, grantResults);
                    }
                }
    
                if (mRemovedPermissionsResults != null && mRemovedPermissionsResults.size() > 0) {
                    if (mPermissionsResults.removeAll(mRemovedPermissionsResults)) {
                        mRemovedPermissionsResults.clear();
                    }
                }
            }
        }
    
        public void addOnActivityPermissionsResults(InnerOnRequestPermissionsResult innerOnRequestPermissionsResult) {
            if (mPermissionsResults != null) {
                mPermissionsResults.add(innerOnRequestPermissionsResult);
            }
        }
    
        public void removeOnActivityPermissionsResults(InnerOnRequestPermissionsResult innerOnRequestPermissionsResult) {
            if (mPermissionsResults != null && mRemovedPermissionsResults != null) {
                mRemovedPermissionsResults.add(innerOnRequestPermissionsResult);
            }
        }
    }
    
    • InnerOnRequestPermissionsResult

    将Activity的方法提取成接口

    public interface InnerOnRequestPermissionsResult {
        void onRequestPermissionsResult(int var1, String[] var2, int[] var3);
    }
    

    对!实现一共就4个类,下面是Demo

    Activity的入口可以写在BaseActivity里面,当然不然你也可以在每一个需要的Activity里面加这行

    public class BaseActivity extends Activity {
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            RunTimePermissionManager.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    
    • 具体代码实现处
            new IAction() {
                @Override
                public boolean call() {
                    //权限保护的代码,原本逻辑代码
                    return false;
                }
            }.setParent(new IPermissionAction(DemoActivity.this) {
                @Override
                public String getRequestPermission() {
                    //需要申请的权限
                    return Manifest.permission.WRITE_EXTERNAL_STORAGE;
                }
            }).run();
    

    当一个复杂功能逻辑可能需要多个权限的时候,你只要写多几个IPermissionAction就可以了,之后你需要的权限交互方面,你只要在IPermissionAction的
    onPermissionAlwaysDenied()
    onPermissionDenied()
    onPermissionUnable()
    方法中处理就好了。

    代码在这里

    相关文章

      网友评论

          本文标题:Android M 运行时权限“快速”适配

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