📌  相关文章
📜  如何在Android中以编程方式使用音量键增加/降低屏幕亮度?

📅  最后修改于: 2021-05-10 17:49:32             🧑  作者: 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.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
        )
    }
}


步骤3:使用activity_main.xml文件

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

输出:在模拟器上运行

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

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