Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
How to Increase/Decrease Screen Brightness using Volume Keys Programmatically in Android?
Next article icon

How to Maximize/Minimize Screen Brightness Programmatically in Android?

Last Updated : 19 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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. Applications Streaming Videos: Each frame could be analyzed and compared with the ambient light of the room and accordingly make changes while viewing it to the users.
  2. Low Battery Situations: Brightness can be set at a low value if the battery level is low.
  3. If the screen is inactive or unresponded: If the screen is inactive or unresponded, the brightness could be lowered after a specific time-out.

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.

Step-by-Step Implementation of Screen Brightness Programmatically in Android

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 you 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. 

AndroidManifest.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.playingwithbrightness">        <!--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

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.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <!--This button will make the brightness minimum-->     <Button         android:id="@+id/turn_off_screen_button"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_centerInParent="true"         android:text="Turn Off Screen"         tools:ignore="MissingConstraints" />      <!--This button will make the brightness maximum-->     <Button         android:id="@+id/turn_on_screen_button"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_below="@id/turn_off_screen_button"         android:layout_centerHorizontal="true"         android:text="Turn On Screen"         tools:ignore="MissingConstraints" />  </RelativeLayout> 

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.

MainActivity.kt
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 androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity  class MainActivity : AppCompatActivity() {     @RequiresApi(Build.VERSION_CODES.M)     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          // Get turn off screen button         val turnOffScreenButton: Button = findViewById(R.id.turn_off_screen_button)         turnOffScreenButton.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 they Can modify system settings panel.             if (!settingsCanWrite) {                 changeWriteSettingsPermission(context)             } else {                 changeScreenBrightness(context, 1)             }         }                  // Get turn on screen button         val turnOnScreenButton: Button = findViewById(R.id.turn_on_screen_button)         turnOnScreenButton.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 {                 changeScreenBrightness(context, 255)             }         }     }      // 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.


Next Article
How to Increase/Decrease Screen Brightness using Volume Keys Programmatically in Android?
author
aashaypawar
Improve
Article Tags :
  • Kotlin
  • Android

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
  • How to Resize Images Programmatically in Android?
    There are many applications available on the net for performing image operations such as cropping, reducing image file size, or resizing the images to particular dimensions. Most of these applications are API based where the image is uploaded to anonymous servers, various functions are performed and
    3 min read
  • How to Increase/Decrease Screen Brightness using Volume Keys 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
  • How to Get RAM Memory in Android Programmatically?
    RAM (Random Access Memory) of a device is a system that is used to store data or information for immediate use by any application that runs on the device. Every electronic device that runs a program as a part of its application has some amount of RAM associated with it. Mobile devices nowadays come
    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 Get Internal Memory Storage Space in Android Programmatically?
    Every device has an internal memory where it can store files and applications. The internal memory of devices can vary anywhere between 4 GB to 512GB. As internal memory gets filled up with a stack of files and applications, the available space decreases. Developers, to save internal memory, design
    3 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
  • How to Detect Touch Event on Screen Programmatically in Android?
    Detecting a touch confirms that the screen is fully functional. Responding to touch is something that a developer deals with. As Android devices have a touch-based input, things are programmed upon application of touch. For explicitly calling methods within the application, a touch action must be re
    5 min read
  • How to Take Screenshot Programmatically in Android?
    In every android phone, we have feature to take screenshots of screens. In this article, we are going to explain how to take screenshots programmatically. Step-by-Step ImplementationStep 1: Create a New ProjectTo create a new project in Android Studio please refer to How to Create/Start a New Projec
    4 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences