•• Kotlin Version in Simple Steps
次の手順を実行します:
1.manifest.xml
通常、権限の使用要素を追加します。
<uses-permission
android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
2.設定を変更する場合は、書き込みアクセスを確認します。
if (context.canWriteSettings) {
} else {
startManageWriteSettingsPermission()
}
3.許可を要求する場合は、次のコード行も追加します。
private fun startManageWriteSettingsPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent(
Settings.ACTION_MANAGE_WRITE_SETTINGS,
Uri.parse("package:${context.packageName}")
).let {
startActivityForResult(it, REQUEST_CODE_WRITE_SETTINGS_PERMISSION)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_CODE_WRITE_SETTINGS_PERMISSION -> {
if (context.canWriteSettings) {
} else {
Toast.makeText(context, "Write settings permission is not granted!", Toast.LENGTH_SHORT).show()
}
}
}
}
val Context.canWriteSettings: Boolean
get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(this)
companion object {
private const val REQUEST_CODE_WRITE_SETTINGS_PERMISSION = 5
}