Related Articles

Related Articles

How to Increase/Decrease Screen Brightness in Steps Programmatically in Android?
  • Last Updated : 14 Oct, 2020

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?

  1. Video Player: Brightness could be increased or decreased in steps directly from the video player.
  2. Games: Brightness could be increased or decreased in steps directly from the game.
  3. Book Reader Applications: Reading books can sometimes be a moody choice, one can increase or decrease brightness directly from the application in steps.

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.

Sample gif

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<manifest 
    xmlns:tools="http://schemas.android.com/tools"
    package="org.geeksforgeeks.screenbrightness_incdecremental">
    
      <!--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>

chevron_right


Step 3: Working with the activity_main.xml file

Next, go to the activity_main.xml file, which represents the UI of the project. Add two Buttons as shown, one to make the brightness value maximum and the other to make it minimum. Below is the code for the activity_main.xml file.

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--Button to decrease the screen brightness-->
    <Button
        android:id="@+id/decreaseBrightness"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="-"
        tools:ignore="MissingConstraints" />
  
    <!--Button to increase the screen brightness-->
    <Button
        android:id="@+id/increaseBrightness"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/decreaseBrightness"
        android:layout_centerHorizontal="true"
        android:text="+"
        tools:ignore="MissingConstraints" />
  
</RelativeLayout>

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.Button
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import java.lang.Math.round
  
class MainActivity : AppCompatActivity() {
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        var brightnessValue = 255
  
        // decrease brightness button
        val decBrightness: Button = findViewById(R.id.decreaseBrightness)
        decBrightness.setOnClickListener { // 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 {
                // brightness cannot be less than 0 and every click decreases the brightness
                // by a value of 10
                if (brightnessValue >= 11) {
                    brightnessValue -= 10
                    changeScreenBrightness(context, brightnessValue)
  
                    // Brightness value (1-255) to percentage and output as a Toast
                    val k = brightnessValue.toDouble() / 255
                    Toast.makeText(
                        applicationContext, "Brightness : ${round(k * 100)}%",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
  
        // increase brightness button
        val incBrightness: Button = findViewById(R.id.increaseBrightness)
        incBrightness.setOnClickListener {
            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 {
                // brightness cannot be more than 255 and every click increases the
                // brightness by a value of 10
                if (brightnessValue <= 245) {
                    brightnessValue += 10
                    changeScreenBrightness(context, brightnessValue)
  
                    // Brightness value (1-255) to percentage and output as a Toast
                    val k = brightnessValue.toDouble() / 255
                    Toast.makeText(
                        applicationContext, "Brightness : ${round(k * 100)}%",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }
  
    // 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
        )
    }
}

chevron_right


Output: Run on Emulator

Note that before running the application make sure you have granted the required permissions otherwise the application will be crashed.




My Personal Notes arrow_drop_up
Recommended Articles
Page :