淘先锋技术网

首页 1 2 3 4 5 6 7

第一步:在gradle中导入EasyPermissions库依赖

implementation 'pub.devrel:easypermissions:1.1.3'

第二步 :Activity或者Fragment实现EasyPermissions.PermissionCallbacks接口,并重写接口里的两个方法,如下:

//授权成功后回调
override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>?) {
        if (requestCode== REQUEST_PERMISSION_TAG)
        {
            startActivity(Intent(this@SplashScreenActivity, HomeActivity::class.java))
            finish()
        }
    }


//拒绝权限后回调
 override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) { 
            // 设置"不要再询问",必须手动到系统设置授权
           // 这里可以显示一个弹窗引导用户跳转到统设置授权
        } else {
            //拒绝授权后可以弹出一个窗口提示重新获取权限
        }
    }

第三步:在需要运行时权限的地方法中检查权限

       // 检查权限,其中mPermissions代表需要申请的权限String数组
        if (EasyPermissions.hasPermissions(this, *mPermissions)) {//已授权
            window.decorView.postDelayed({
               startActivity(Intent(this@SplashScreenActivity,HomeActivity::class.java))
                finish()
            }, 1000L)
        } else {//未授权
            ActivityCompat.requestPermissions(this, mPermissions,REQUEST_PERMISSION_TAG)
        }

四:最重要的一步,在Activity的onRequestPermissionsResult()方法中将授权结果回调传给EasyPermissions,然后EasyPermissions就会根据是否授权回调onPermissionsDenied()或onPermissionsGranted()方法

  override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
      EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this)
    }

五:当用户跳转到系统设置授权时返回时,也可以在onActivityResult()中判断一下用户有没有授权,如下:

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==1111)
        {
            if (EasyPermissions.hasPermissions(this, *mPermissions)) {
                    startActivity(Intent(this@SplashScreenActivity, HomeActivity::class.java))
                    finish()
            } else {
                ActivityCompat.requestPermissions(this, mPermissions, REQUEST_PERMISSION_TAG)
            }
        }
    }