import
android.content.Context
import
android.content.Intent
import
android.os.Build
import
android.os.Bundle
import
android.provider.Settings
import
android.widget.Button
import
android.widget.Toast
import
androidx.annotation.RequiresApi
import
androidx.appcompat.app.AppCompatActivity
import
java.lang.Math.round
class
MainActivity : AppCompatActivity() {
@RequiresApi
(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super
.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var brightnessValue =
255
val decBrightness: Button = findViewById(R.id.decreaseBrightness)
decBrightness.setOnClickListener {
val context = applicationContext
val settingsCanWrite = hasWriteSettingsPermission(context)
if
(!settingsCanWrite) {
changeWriteSettingsPermission(context)
}
else
{
if
(brightnessValue >=
11
) {
brightnessValue -=
10
changeScreenBrightness(context, brightnessValue)
val k = brightnessValue.toDouble() /
255
Toast.makeText(
applicationContext,
"Brightness : ${round(k * 100)}%"
,
Toast.LENGTH_SHORT
).show()
}
}
}
val incBrightness: Button = findViewById(R.id.increaseBrightness)
incBrightness.setOnClickListener {
val context = applicationContext
val settingsCanWrite = hasWriteSettingsPermission(context)
if
(!settingsCanWrite) {
changeWriteSettingsPermission(context)
}
else
{
if
(brightnessValue <=
245
) {
brightnessValue +=
10
changeScreenBrightness(context, brightnessValue)
val k = brightnessValue.toDouble() /
255
Toast.makeText(
applicationContext,
"Brightness : ${round(k * 100)}%"
,
Toast.LENGTH_SHORT
).show()
}
}
}
}
@RequiresApi
(Build.VERSION_CODES.M)
private
fun hasWriteSettingsPermission(context: Context): Boolean {
var ret =
true
ret = Settings.System.canWrite(context)
return
ret
}
private
fun changeWriteSettingsPermission(context: Context) {
val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
context.startActivity(intent)
}
private
fun changeScreenBrightness(context: Context, screenBrightnessValue: Int) {
Settings.System.putInt(
context.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
)
Settings.System.putInt(
context.contentResolver,
Settings.System.SCREEN_BRIGHTNESS, screenBrightnessValue
)
}
}