【Android开发】EasyPermissions 请求权限

安卓6.0以后,开发应用的时候,仅在AndroidManifest.xml中申请权限已经不可以了,需要在代码中动态申请。

现在看一个google推出的机制:EasyPermissions

引入步骤:

1. 导入库文件:
dependencies {
    compile 'pub.devrel:easypermissions:1.0.1'
}
2. 实现 EasyPermissions.PermissionCallbacks
public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    String[] perms = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION};

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

        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            // ...
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.camera_and_location_rationale),
                RC_CAMERA_AND_LOCATION, perms);
        }
    }

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

        // 将权限的处理交给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
        // ...
    }
}

流程讲解:

  1. 首先通过EasyPermissions.hasPermissions(this, perms),查看是否已经获取了权限;
  2. 如果没有授权,则通过 EasyPermissions.requestPermissions(.....)方法请求权限;
  3. 处理请求的是onRequestPermissionsResult,它会将处理转交给EasyPermissions.onRequestPermissionsResult(.....);
  4. 获取处理结果,如果授权,则执行onPermissionsGranted,未授权,则执行onPermissionsDenied;

Git地址请见:https://github.com/googlesamples/easypermissions#installation

posted @ 2018-12-27 14:52  浪里小白龙呼呼呼  阅读(1687)  评论(0编辑  收藏  举报