How to Increase/Decrease Screen Brightness using Volume Keys Programmatically in Android?
Last Updated :
16 Aug, 2024
Screen brightness is one such factor that directly affects the Users as well as the Battery on a device. Android devices are Smart systems and have an inbuilt system for Auto-Brightness. But mostly this feature is unchecked by the users or set off by default. Irrespective of whether this feature is present, set on or off, or absent in any device, a developer must take this opportunity into consideration and develop an optimized application. Anything that is declared inside the application might have an effect on the outside space, i.e., if the screen brightness was changed programmatically from an application, the brightness value might stay unaltered even after exiting the application. So one must try to trace back the originals and set them before a user exits.
Where can we use this feature?
- Non-Media: Non-media (music or video) applications could use the volume buttons to increase or decrease the brightness of a screen in steps.
- Book Reader Applications: Reading books can sometimes be a moody choice, one can increase or decrease brightness directly from the application in steps.
- News Paper Applications: One can increase or decrease brightness directly from the application in steps.
Through this article, we want you to know that volume buttons could be used for increasing and decreasing the brightness of a screen. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Approach
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the AndroidManifest.xml file
Controlling the device screen brightness requires a change in root settings, for which declare a uses-permission of WRITE_SETTINGS in the AndroidManifest.xml file.
<uses-permission android:name=”android.permission.WRITE_SETTINGS”
tools:ignore=”ProtectedPermissions” />
Below is the code for the AndroidManifest.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="org.geeksforgeeks.screenbrightness_usingvolumekeys">
<!--Add this permission-->
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 3: Working with the activity_main.xml file
There is nothing to do with the activity_main.xml file. So keep the file as it is.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Working with the MainActivity.kt file
Finally, go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.KeyEvent
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.round
class MainActivity : AppCompatActivity() {
var brightnessValue = 255
@RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
// Function to decrease the brightness
@RequiresApi(Build.VERSION_CODES.M)
fun decrease() { // Get app context object.
val context = applicationContext
// Check whether has the write settings permission or not.
val settingsCanWrite = hasWriteSettingsPermission(context)
// If do not have then open the Can modify system settings panel.
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()
}
}
}
// Function to increase the brightness
@RequiresApi(Build.VERSION_CODES.M)
fun increase() {
val context = applicationContext
// Check whether has the write settings permission or not.
val settingsCanWrite = hasWriteSettingsPermission(context)
// If do not have then open the Can modify system settings panel.
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()
}
}
}
// Listen to the volume keys
@RequiresApi(Build.VERSION_CODES.M)
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
// What happens when volume down key is pressed
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
decrease()
}
// What happens when volume up key is pressed
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
increase()
}
return true
}
// Check whether this app has android write settings permission.
@RequiresApi(Build.VERSION_CODES.M)
private fun hasWriteSettingsPermission(context: Context): Boolean {
var ret = true
// Get the result from below code.
ret = Settings.System.canWrite(context)
return ret
}
// Start can modify system settings panel to let
// user change the write settings permission.
private fun changeWriteSettingsPermission(context: Context) {
val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
context.startActivity(intent)
}
// This function only take effect in real physical android device,
// it can not take effect in android emulator.
private fun changeScreenBrightness(context: Context, screenBrightnessValue: Int) {
// Change the screen brightness change mode to manual.
Settings.System.putInt(
context.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
)
// Apply the screen brightness value to the system, this will change
// the value in Settings ---> Display ---> Brightness level.
// It will also change the screen brightness for the device.
Settings.System.putInt(
context.contentResolver, Settings.System.SCREEN_BRIGHTNESS,
screenBrightnessValue
)
}
}
Output: Run on Emulator
Note that before running the application make sure you have granted the required permissions otherwise the application will be crashed.
Similar Reads
How to Increase/Decrease Screen Brightness in Steps Programmatically in Android?
Screen brightness is one such factor that directly affects the Users as well as the Battery on a device. Android devices are Smart systems and have an inbuilt system for Auto-Brightness. But mostly this feature is unchecked by the users or set off by default. Irrespective of whether this feature is
5 min read
Increase or Decrease the Volume Programmatically in Android using Jetpack Compose
Many times while building an android application such as using an audio player like a music player. We have to add functionality to add a volume controller for our media player within our application. So that we can control the volume of our media player. In this article, we will take a look at How
6 min read
How to Maximize/Minimize Screen Brightness Programmatically in Android?
Screen brightness is one such factor that directly affects the users as well as the battery on a device. Android devices are Smart systems and have an inbuilt system for Auto-Brightness. But mostly this feature is unchecked by the users or set off by default. Irrespective of whether this feature is
4 min read
How to Increase or Decrease TextView Font Size in Android Programmatically?
In this App, we are going to learn how to increase or decrease TextView Font Size in Android programmatically. Like we have seen that in many apps we sometimes want to enlarge the text. So here basically we are going to implement that. A sample GIF is given below to get an idea about what we are goi
3 min read
How to Change the Screen Orientation Programmatically using a Button in Android?
Generally, the screen orientation of any application is Portrait styled. But when it comes to gaming or any other multimedia service such as watching a video, the screen orientation must change functionally from Portrait to landscape or vice-versa when the functionality is not required. So a develop
3 min read
Increase or Decrease Brightness in Android using Jetpack Compose
Screen brightness is adjusted in many android applications while interacting with the screens. In the application, if we are displaying a QR code in that case we have to increase the screen brightness so that the QR code will be properly visible to the scanner. In this article, we will take a look a
3 min read
How to Find Dots-Per-Inch (DPI) of Screen in Android Programmatically?
Dots-Per-Inch or DPI is a measure of pixel density over the physical area on the screen. A pixel is the smallest unit of any screen display. and the sum of all the pixels present on the screen is termed as Screen Resolution. The pixels available to the user are called Viewport and in this article, w
2 min read
How to Listen for Volume Button and Back Key Events Programmatically in Android?
By production, Android devices are provided with specific physical keys, such as Volume keys, Power key, Back key, Home key, and Activities key. These keys respond to a press. The same keys have particular functionality on the nature of the press. The volume key on a Single press increases or decrea
3 min read
How to Change the Whole App Language in Android Programmatically?
Android 7.0(API level 24) provides support for multilingual users, allowing the users to select multiple locales in the setting. A Locale object represents a specific geographical, political, or cultural region. Operations that require these Locale to perform a task are called locale-sensitive and u
5 min read
How to Check the Battery Level in Android Programmatically?
Sometimes, it is useful to determine the current battery level. One may choose to reduce the rate of your background updates if the battery charge is below a certain level. But one cannot continuously monitor the battery state. In general, the impact of constantly monitoring the battery level has a
2 min read