I added SeekBar in Android
app. I'm able to change the brightness of the system using SeekBar
.
binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
@RequiresApi(api = Build.VERSION_CODES.M)
override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
val permission = Settings.System.canWrite(applicationContext)
if (permission) {
var brightnessValue = p1 * 255 / 100
Settings.System.putInt(
applicationContext.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC)
Settings.System.putInt(contentResolver, SCREEN_BRIGHTNESS, brightnessValue)
binding.seekBar.progress = brightnessValue
} else {
val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
intent.data = Uri.parse("package:" + applicationContext.packageName)
startActivityForResult(intent, 0)
}
}
override fun onStartTrackingTouch(p0: SeekBar?) {
}
override fun onStopTrackingTouch(p0: SeekBar?) {
}
})
This is how I can see the change in the system on the SeekBar
.
val contentObserver: ContentObserver = object : ContentObserver(Handler()) {
override fun onChange(selfChange: Boolean) {
val a = Settings.System.getInt(contentResolver, SCREEN_BRIGHTNESS, 0)
Log.d("MainActivity", "Brightness value: $a")
binding.seekBar.progress = a* 255 / 100
}
}
contentResolver.registerContentObserver(
Settings.System.getUriFor(SCREEN_BRIGHTNESS),
false, contentObserver
)
It is specific for some Xiaomi devices. For example Xiaomi Redmi Note 7 has 0-4000
range. Official documentation defines SCREEN_BRIGHTNESS range as 0-255
. So, I think there are no API to get the maximum value in brightness.
When I use both together, the code doesn't work. How I can get it to work correctly both when I change it from the system and when I change it on the SeekBar
?