EasyPermissions 动态申请权限使用

EasyPermissions 的github地址是:https://github.com/googlesamples/easypermissions 

EasyPermissions 最新版本查询  https://mvnrepository.com/artifact/pub.devrel/easypermissions?repo=springio-plugins-release

EasyPermissions 集成

dependencies {
 // 权限申请
    compile 'pub.devrel:easypermissions:1.0.1'

}

 

EasyPermissions  使用

请求权限

public class MainActivity extends AppCompatActivity  implements EasyPermissions.PermissionCallbacks {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String[] perms = { Manifest.permission.ACCESS_FINE_LOCATION , Manifest.permission.ACCESS_COARSE_LOCATION };
        if (EasyPermissions.hasPermissions( MainActivity.this , perms)) {
        // Already have permission, do the thing
        } else {
        // Do not have permissions, request them now
        EasyPermissions.requestPermissions( MainActivity.this, "需要定位权限" , PERMISSIONS_ACCESS_LOCATION, perms);
        }

    }

    @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 perms) {
        // 此处表示权限申请已经成功,可以使用该权限完成app的相应的操作了
        Log.e(TAG , "同意了 权限申请" );
    }

    @Override
    public void onPermissionsDenied(int requestCode, List perms) {
        // 此处表示权限申请被用户拒绝了,此处可以通过弹框等方式展示申请该权限的原因,以使用户允许使用该权限

        //(可选的)检查用户是否拒绝授权权限,并且点击了“不再询问”(测试如果不点击 不再询问也会调用这个方法,所以只要拒绝就会调用这个方法)
        //下面的语句,展示一个对话框指导用户在应用设置里授权权限
        Log.e(TAG , "拒绝了 权限申请" );
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("申请权限")
                    .setRationale("应用需要这个权限")
                    .build()
                    .show();
            Log.e(TAG , "引导设置 申请权限" );
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            // Do something after user returned from app settings screen, like showing a Toast.
            // 当用户从应用设置界面返回的时候,可以做一些事情,比如弹出一个土司。
            Toast.makeText(this, "权限设置界面返回" , Toast.LENGTH_SHORT).show();
        }

    }

 

 

你可能感兴趣的:(Android)