脱掉RxPermission的嫁衣

permission.jpeg

  Android 6.0权限管理的接入方式有点累,这模式跟ActivityResult一样的实现方式,请求和接收是分离的,没有挂回调函数那么方便,当页面代码量大的时候阅读性不好:

private void requestPermission(){
    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {
        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed, we can request the permission.
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

  因为跟ActvitiyResult一个模式,请求返回结果是以数组方式提供的, 想知道所有结果是否都grant得要遍历数组一一比较grantResults,想知道究竟哪个权限被拒绝,也要遍历permissions并判断同样index对应的grantResults结果。
  其实,因为业务代码比较多,大家想拥有的请求权限的API如下那么简单:

// 只关注全部授权通过
requestPermission(new OnGrantResult() {
        @Override
        public void onGrant() {
            // do something when grant
        }

         @Override
         public void onDenied() {
             // do something when denied
         }
    }, Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_PHONE_STATE);

// 关注个别权限授权结果
requestEachPermission(new OnEachGrantResult() {
        @Override
        public void onNext(Permission permission) {
            // check someone permission and
            // its grant state and do something you want
        }
    }, Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_PHONE_STATE);

说到封装,如上API,可能很多人感觉不难,可能很多人都想到的办法是:

  1. 改BaseActivity和BaseFragment并在其中添加新的API:requestPermissions(OnGrantResult result, String... permissions)
  2. 然后在BaseActivity和BaseFragment 复写 onRequestPermissionsResult(), 并在其中遍历grantResults数组,只有全部都等于PackageManager.PERMISSION_GRANTED则最终通过request在map中找到OnGrantResult触发回调以此告知子Activity或者Fragment是全部授权成功的,否则授权失败。

  看似完美,但是有一个最大的问题是代码嵌入性太强,BaseActivity和BaseFragment实在太臃肿,一有类似的功能增加就想动它们,可能有些朋友认为,BaseActivity或者BaseFragment可以搞多层继承啊,这样每一层只做对应的事情,比如把权限相关的封装在一个BasePermissionActivity里,然后BaseActivity继承BasePermissionActivity里,可是时间长了你会发现BaseActivity的搞了很多层,一有新功能就加层级,说实话层级依赖不如扁平依赖。
  前段时间在看RxJava原理的时候顺便看到了衍生作品RxPermission,发现它非常奇妙,通过RxPermission请求权限无需改变BaseActivity又能以挂回调方式接收请求结果,想看究竟内部是怎么做到的。
  看完之后的感慨是:好吧,RxJava的确很强大,不过RxPermission里的Rx只是一个障眼法,本质原理是在需要请求权限的Activity打开一个无UI的Fragment或者在需要请求权限的Fragment里打开一个无UI的Child Fragment,并在打开的Fragment里请求权限,因为Fragment和它的宿主天生能进行通信,所以在无UI的Fragment里请求权限并把授权结果告知它宿主即需要权限的Activity或者Fragment。
  知道这个原理后,如果不希望在自己项目中引入RxJava你就可以自己简化RxPermission了,其实很简单,保留一个用于权限请求的fragment和权限请求器之间的callback即可。

简化后的代码少之又少:
struct.png

简化后的使用如下:

public class MainActivity extends AppCompatActivity {
    private Permissions mPermissions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // init permissions
        mPermissions = new Permissions(this);

        Button requestBtn = findViewById(R.id.requestBtn);
        requestBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPermissions.request(new OnGrantResult() {
                    @Override
                    public void onGrant() {
                        // do something when grant
                    }

                     @Override
                     public void onDenied() {
                         // do something when denied
                     }
                }, Manifest.permission.READ_CONTACTS,
                        Manifest.permission.READ_PHONE_STATE);
            }
        });

        Button requestEachBtn = findViewById(R.id.requestEachBtn);
        requestEachBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPermissions.requestEach(new OnEachGrantResult() {
                    @Override
                    public void onNext(Permission permission) {
                        // check someone permission and
                        // its grant state and do something you want
                    }
                }, Manifest.permission.READ_CONTACTS,
                        Manifest.permission.READ_PHONE_STATE);
            }
        });
    }
}

详细实现可以参考这里,同样的原理也实现了以挂回调方式接收startActivityForResult()的结果,又同时简化了以前的一篇文章介绍的打开页面自动登录并回来-拦截器(升级版),有一种触类旁通的感觉。

你可能感兴趣的:(脱掉RxPermission的嫁衣)