Android6.0动态权限申请
github 地址
通过Fragment实现权限申请
检测权限
- 通过ContextCompat / ActivityCompat的checkSelfPermission检查权限状态
- 通过Context / Fragment的checkPermission / checkSelfPermission(API 23)检查权限状态
申请权限
- 通过Activity / Fragment的requestPermissions(API 23)申请权限
- 通过ActivityCompat的requestPermissions申请权限
权限申请结果
- 通过重写Activity / Fragment的onRequestPermissionsResult函数获取申请结果grantResults返回值都为PackageManager.PERMISSION_GRANTED时则所有权限通过
封装后的使用
//申请权限
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
this.apply(Manifest.permission.READ_EXTERNAL_STORAGE) { reject, forever ->
forever.forEach {
println("永久拒绝的权限:$it")
}
if (reject.isEmpty()) {
println("ok")
} else {
println("no")
}
}
}
}
//批量申请权限
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
this.apply(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { reject, forever ->
forever.forEach {
println("永久拒绝的权限:$it")
}
if (reject.isEmpty()) {
println("ok")
} else {
println("no")
}
}
}
}
//申请apk安装权限
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
this.applyInstallPackage { reject, _ ->
if (reject.isEmpty()) {
println("ok")
} else {
println("no")
}
}
}
}
//打开app设置页
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
this.openAppSettings()
}
}
网友评论