The effect
Changing the brightness of the system screen is quite common and is generally involved in multimedia development.
Emmm renderings don’t seem to show the changes. But it’s not very important.
Operation and dismantling
As you can see in the image above, there are addition and subtraction buttons and seekbar to control brightness.
Related events will be covered later.
Gets the system screen brightness
/** * Get system screen brightness (0-255) */
private fun getScreenBrightness(a): Int {
try {
return Settings.System.getInt(this.contentResolver, Settings.System.SCREEN_BRIGHTNESS)
} catch (e: SettingNotFoundException) {
e.printStackTrace()
}
return 0
}
Copy the code
Note that the return value is in the range 0-255.
Define two parameters:
- Private var mScreenBrightness: Int = 0 // Current Screen brightness
- Private var ratio: Int = 25
Since the maximum return value is 255, assuming that the brightness adjustment is 10 steps, adding or subtracting one step at a time is about 25. This precision can be controlled by yourself.
This parameter is valid only for the current application screen brightness
Add and subtract button operation
btn_add.setOnClickListener {
if (mScreenBrightness < (255 - ratio)) {
mScreenBrightness += ratio
} else {
mScreenBrightness = 255
}
setWindowBrightness(mScreenBrightness)
updateNum(mScreenBrightness)
}
btn_reduce.setOnClickListener {
if (mScreenBrightness > ratio) {
mScreenBrightness -= ratio
} else {
mScreenBrightness = 1
}
setWindowBrightness(mScreenBrightness)
updateNum(mScreenBrightness)
}
Copy the code
If the value of brightness is greater than 255, no error will be reported, but the initial value will be returned, so when adding or subtracting, determine the maximum value and minimum value.
What is the core method setWindowBrightness?
/** * Sets the current app screen brightness
private fun setWindowBrightness(brightness: Int) {
val window = window
val lp = window.attributes
lp.screenBrightness = brightness / 255.0 f
window.attributes = lp
}
Copy the code
Simply set the properties of the window. This will only apply to the current page, and the screen brightness will be restored to its initial state if you go back to the page or back to the background.
UpdateNum Update page display:
/** * Update the page display */
private fun updateNum(mScreenBrightness: Int) {
// Round to float
val i: Int = (mScreenBrightness / (ratio.toFloat())).roundToInt()
tv_brightness.text = i.toString()
seekBar.progress = i
}
Copy the code
In fact, at this point, most of our needs are satisfied.
Making: github.com/yechaoa/Bri…
Set system screen brightness to affect all pages and APPS
What I mentioned above is actually the brightness setting of a single page. You can also modify the screen brightness of the system, that is, affecting all pages and apps. Generally, this operation will not happen. This also involves an advanced privacy permission, whether to modify the system Settings, and requires manual authorization on the APP Settings page.
Add the following to the manifest:
<! -- Change system screen brightness --> <uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
Copy the code
Here are a few small steps:
- Judge authority
- If yes, modify the brightness
- If no, boot authorization
SeekBar operation
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar? , progress:Int, fromUser: Boolean) {
Log.i("onProgressChanged----"."" + progress)
mScreenBrightness = progress * ratio
// Check whether you have permission to modify system Settings
if (Settings.System.canWrite(this@BrightnessActivity)) {
setScreenBrightness(mScreenBrightness)
updateNum(mScreenBrightness)
} else {
Toast.makeText(this@BrightnessActivity."No modification permission", Toast.LENGTH_SHORT).show()
// Open the page that allows you to modify system Settings
val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:$packageName"))
startActivityForResult(intent, mRequestCode)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?).{}override fun onStopTrackingTouch(seekBar: SeekBar?).{}})Copy the code
Use settings.system. canWrite to determine whether authorization is granted.
Have authorized
What is the setScreenBrightness method?
/** * Set system screen brightness, affecting all pages and app * Note: this method requires manual permission (Android.permission.WRITE_SETTINGS) */
private fun setScreenBrightness(brightness: Int) {
try {
// Check the adjustment mode first
setScreenManualMode()
/ / set up again
Settings.System.putInt(this.contentResolver, Settings.System.SCREEN_BRIGHTNESS, brightness)
} catch (e: SettingNotFoundException) {
e.printStackTrace()
}
}
Copy the code
We see that the next step before setting is to check the adjustment mode, because if the current brightness is automatically adjusted, you need to change it to manual.
/** * Set the system brightness adjustment mode (SCREEN_BRIGHTNESS_MODE) * SCREEN_BRIGHTNESS_MODE_MANUAL Manual SCREEN_BRIGHTNESS_MODE_AUTOMATIC automatic adjustment */
private fun setScreenManualMode(a) {
try {
// Get the current system brightness adjustment mode
val mode = Settings.System.getInt(this.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE)
// If it is automatic, change it to manual
if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
Settings.System.putInt(
this.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
)
}
} catch (e: SettingNotFoundException) {
e.printStackTrace()
}
}
Copy the code
Brightness mode
- SCREEN_BRIGHTNESS_MODE_MANUAL Manual adjustment
- SCREEN_BRIGHTNESS_MODE_AUTOMATIC Automatic adjustment
unauthorized
Prompt and guide the user to authorize when not authorized
Toast.makeText(this@BrightnessActivity."No modification permission", Toast.LENGTH_SHORT).show()
// Open the page that allows you to modify system Settings
val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:$packageName"))
startActivityForResult(intent, mRequestCode)
Copy the code
At the same time, the results can be detected and processed
/** * process the result */
override fun onActivityResult(requestCode: Int, resultCode: Int.data: Intent?). {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == mRequestCode) {
if (Settings.System.canWrite(this@BrightnessActivity)) {
setScreenBrightness(mScreenBrightness)
} else {
Toast.makeText(this@BrightnessActivity."Denied access.", Toast.LENGTH_SHORT).show()
}
}
}
Copy the code
As can be seen from the above, Settings.System. PutInt is used to change the mode and brightness, which is to change the System Settings so that all pages and apps can use the same brightness.
Monitor system brightness change
In fact, the above two ways are manual to change, that if the user to change the brightness, we should also make corresponding changes to the page, so, also need to monitor the system brightness changes.
There are a few small steps:
- Register to monitor
- Dealing with change
- Cancellation of listening
Register to monitor
/** * Register to listen for system screen brightness changes */
private fun registerContentObserver(a) {
this.contentResolver? .registerContentObserver( Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS),true,
mBrightnessObserver
)
}
Copy the code
Dealing with change
/** * monitor system brightness change */
private val mBrightnessObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
override fun onChange(selfChange: Boolean) {
super.onChange(selfChange)
try {
this@BrightnessActivity.contentResolver? .let { mScreenBrightness = Settings.System.getInt(it, Settings.System.SCREEN_BRIGHTNESS) updateNum(mScreenBrightness) setWindowBrightness(mScreenBrightness) } }catch (e: SettingNotFoundException) {
e.printStackTrace()
}
}
}
Copy the code
Cancellation of listening
override fun onDestroy(a) {
super.onDestroy()
// Unlog the listener
this.contentResolver? .unregisterContentObserver(mBrightnessObserver) }Copy the code
Ok, so that’s the end of the discussion about changing the brightness of the screen. If it worked for you, give it a thumbs up
Github
Github.com/yechaoa/Bri…