Android开源项目-Easypermissions

0.181字数 361阅读 35348

Easypermissions简化了Android M的运行时权限的申请、结果处理、判断等步骤。

1 相关文档

官方文档:

https://github.com/googlesamples/easypermissions

运行时权限官方文档解释:

https://developer.android.com/training/permissions/requesting.html

2 为什么使用Easypermissions

Android M对权限系统进行了改变。Android M之前所需权限只需要在AndroidManifest中申请即可。但更新Android M系统后,部分“Dangerous Permission”需要在运行时询问申请。

Normal and Dangerous Permissions解释:
https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous

如下图所示:

运行时权限申请

代码中如果需要申请运行时权限步骤:

1 检查运行时权限

ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED

2 申请权限

ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

3 接收权限处理结果

@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
    }
}

以上即是google建议的运行时权限处理过程。代码量和处理地方还是比较繁琐的。so,Easypermissions应运而生。

3 如何使用

首先,引用库

dependencies {
  compile 'pub.devrel:easypermissions:0.1.9'
}

同样,easypermissions处理权限分为3步。

1 检查权限

String[] perms = {Manifest.permission.CAMERA, Manifest.permission.CHANGE_WIFI_STATE};
if (EasyPermissions.hasPermissions(this, perms)) {
   //...     
} else {
    //...
}

2 申请权限

EasyPermissions.requestPermissions(this, "拍照需要摄像头权限",
                    RC_CAMERA_AND_WIFI, perms);

3 实现EasyPermissions.PermissionCallbacks接口,直接处理权限是否成功申请


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //成功
    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Some permissions have been granted
        // ...
    }

    //失败
    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Some permissions have been denied
        // ...
    }

4 总结

Easypermissions主要简化了对权限申请结果的处理和判断,直接以接口的方式回调处理结果。不需要再自行进行处理。

好用指数,5星!!!

结尾

更多文章关注我的公众号


我的公众号

推荐阅读更多精彩内容