As told by OleGG, I tried to do it in "one-line mode", but without any result.
I share with you the only thing that worked for me every single time in API 16 (or greater), using a SeekBar.
I have a companion object in the SettingsActivity
companion object {
private const val WRITE_SETTINGS_PERMISSION = 100
private const val MAX_BRIGHTNESS = 255
private const val MIN_BRIGHTNESS = 20
}
In in the onCreate()
of SettingsActivity
, I call
Settings.System.putInt(this.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
skb_brightness.max = MAX_BRIGHTNESS
skb_brightness.progress = AppPreferences.getInstance(this).brightnessKey
Then I create my listener like this:
object : SeekBar.OnSeekBarChangeListener {
var brightnessProgress = 0
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
brightnessProgress = map(progress, 0, MAX_BRIGHTNESS, MIN_BRIGHTNESS, MAX_BRIGHTNESS)
if (hasPermissionsToWriteSettings(this@SettingsActivity)) {
Settings.System.putInt(this@SettingsActivity.contentResolver, Settings.System.SCREEN_BRIGHTNESS, brightnessProgress)
// Do not write this in one-line, won't work
val lp = this@SettingsActivity.window.attributes
lp.screenBrightness = brightnessProgress.toFloat() / 255
this@SettingsActivity.window.attributes = lp
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?) { }
override fun onStopTrackingTouch(seekBar: SeekBar?) {
AppPreferences.getInstance(this@SettingsActivity).brightnessKey = brightnessProgress
}
}
Where hasPermissionsToWriteSettings(this@SettingsActivity)
is a method that checks if I have permission to do that.
private fun hasPermissionsToWriteSettings(context: Activity): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Settings.System.canWrite(context)
} else {
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED
}
}
The map function is for mapping the min value:
private fun map(currentValue: Int, inputMin: Int, inputMax: Int, outputMin: Int, outputMax: Int): Int {
return (currentValue - inputMin) * (outputMax - outputMin) / (inputMax - inputMin) + outputMin
}
And the AppPreferences
is my helper class to store the value of the brightness in the key-value shared-preferences. It does just this (BRIGHTNESS_CONTROL_KEY = "brightnessControlValue", DEFAULT_BRIGHTNESS = 100)
:
var brightnessKey: Int
get() = sharedPreferences.getInt(BRIGHTNESS_CONTROL_KEY, DEFAULT_BRIGHTNESS)
set(value) = sharedPreferences.edit().putInt(BRIGHTNESS_CONTROL_KEY, value).apply()
I added also in the manifest.xml
:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
...event if Android Studio tolds me that's wrong. Without this, I cannot change brightness.