📌  相关文章
📜  如何在Android中以编程方式逐步增加/减少屏幕亮度?

📅  最后修改于: 2021-05-10 14:49:25             🧑  作者: Mango

屏幕亮度就是直接影响用户以及设备电池的因素之一。 Android设备是智能系统,并且具有用于自动亮度的内置系统。但是大多数情况下,用户未选中此功能,或者默认情况下将其关闭。无论此功能是否存在,设置为打开或关闭,或在任何设备中不存在,开发人员都必须考虑此机会并开发优化的应用程序。在应用程序内部声明的任何内容都可能会对外部空间产生影响,即,如果通过应用程序以编程方式更改了屏幕亮度,则即使退出应用程序后,亮度值也可能保持不变。因此,在用户退出之前,必须尝试回溯原件并进行设置。

我们在哪里可以使用此功能?

  1. 视频播放器:可以直接从视频播放器逐步增加或减少亮度。
  2. 游戏:可以直接从游戏逐步增加或减少亮度。
  3. 图书阅读器应用程序:有时候阅读书籍可能是一种喜怒无常的选择,您可以直接从应用程序中逐步增加或减少亮度。

下面的样本GIF给出得到什么我们将在本文中做的想法请注意,我们将使用Kotlin语言实施此项目。

样本gif

方法

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Kotlin作为编程语言。

步骤2:使用AndroidManifest.xml文件

控制设备屏幕的亮度需要更改根设置,为此需要AndroidManifest.xml文件中声明WRITE_SETTINGS的使用权限。

以下是AndroidManifest.xml文件的代码。

XML


    
      
    
  
    
        
            
                
  
                
            
        
    
  


XML


  
    
    


Kotlin
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
        )
    }
}


步骤3:使用activity_main.xml文件

接下来,转到activity_main.xml文件,该文件代表项目的UI。如图所示,添加两个按钮,一个使亮度值最大,另一个使亮度值最小。以下是activity_main.xml文件的代码。

XML格式



  
    
    

步骤4:使用MainActivity.kt文件

最后,转到MainActivity.kt文件,并参考以下代码。下面是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 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
        )
    }
}

输出:在模拟器上运行

请注意,在运行该应用程序之前,请确保您已授予所需的权限,否则该应用程序将崩溃。

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处前往由我们的专家精心策划的指南,以使您立即做好行业准备!