关注 安卓007 ,免费获取全套安卓开发学习资料
为了更好的保护用户隐私及安全,安卓自6.0版本开始,引入运行时动态权限检查机制.应用需要访问一些涉及用户隐私及安全权限时,应用需要调用系统权限检查接口,查看是否已获得权限,如果没有,则由系统弹出权限申请窗口,由用户决定是否允许使用相应权限.
下面例子中将申请打电话权限并完成打电话功能.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener { applyPermissionAndCall() }
}
/**
* 先检查权限,如果已经获得权限,直接拨打电话;
* 否则申请权限。
*/
private fun applyPermissionAndCall() {
if (hasPermission()) {
call()
} else {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE), 1)
}
}
/**
* 检查是否有权限
*/
private fun hasPermission(): Boolean {
val result = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
return result == PackageManager.PERMISSION_GRANTED
}
/**
* 处理申请权限的结果,如果获得了权限,则拨打电话,否则toast报错。
*/
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
1 -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
call()
} else {
toast("没权限,打不了")
}
}
}
}
/**
* 调用系统打电话功能,拨打10086
*/
private fun call() {
try {
val intent = Intent(Intent.ACTION_CALL)
intent.data = Uri.parse("tel:10086")
startActivity(intent)
} catch (e: SecurityException) {
e.printStackTrace()
}
}
private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
implementation 'com.qw:soulpermission:1.3.0'
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener { applyPermissionAndCall() }
}
/**
* 先申请权限,再打电话
*/
private fun applyPermissionAndCall() {
SoulPermission.getInstance()
.checkAndRequestPermission(
Manifest.permission.CALL_PHONE,
object : CheckRequestPermissionListener {
override fun onPermissionOk(permission: Permission) {
call()
}
override fun onPermissionDenied(permission: Permission) {
toast("没权限,打不了")
}
})
}
/**
* 调用系统打电话功能,拨打10086
*/
private fun call() {
try {
val intent = Intent(Intent.ACTION_CALL)
intent.data = Uri.parse("tel:10086")
startActivity(intent)
} catch (e: SecurityException) {
e.printStackTrace()
}
}
private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
https://gitee.com/cxyzy1/PermissionDemo
Kotlin语言基础
UI控件_TextView
UI控件_EditText
UI控件_Button
UI控件_ImageView
UI控件_RadioButton
UI控件_CheckBox
UI控件_ProgressBar
关注头条号,第一时间获取最新文章: