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?
I don't know what your actual problem is, but if they work separately but not together, you might have a feedback loop where a seekbar change causes a brightness change which causes a seekbar change which causes a brightness change...
If that's the case, you might want to look at your
OnSeekbarChangeListener.onProgressChangedcallback - you can't tell from the parameter names you have there, but the last parameter is a boolean that tells you whether the change was caused by a user interaction (i.e. moving the slider) or not (i.e. the value was set programmatically):So you can check
fromUserinonProgressChanged, and only set the system brightness iffromUseris true - otherwise your update is coming from the brightness change itself, and you don't want to set it again.