以编程方式更改系统亮度 [英] Change the System Brightness Programmatically

查看:33
本文介绍了以编程方式更改系统亮度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式更改系统亮度.为此,我正在使用此代码:

I want to change the system brightness programmatically. For that purpose I am using this code:

WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = (255);
window.setAttributes(lp);

因为我听说最大值是 255.

because I heard that max value is 255.

但它什么都不做.请建议任何可以改变亮度的东西.谢谢

but it does nothing. Please suggest any thing that can change the brightness. Thanks

推荐答案

您可以使用以下内容:

//Variable to store brightness value
private int brightness;
//Content resolver used as a handle to the system's settings
private ContentResolver cResolver;
//Window object, that will store a reference to the current window
private Window window;

在您的 onCreate 中写入:

In your onCreate write:

//Get the content resolver
cResolver = getContentResolver();

//Get the current window
window = getWindow();

    try
            {
               // To handle the auto
                Settings.System.putInt(cResolver,
                Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
 //Get the current system brightness
                brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS);
            } 
            catch (SettingNotFoundException e) 
            {
                //Throw an error case it couldn't be retrieved
                Log.e("Error", "Cannot access system brightness");
                e.printStackTrace();
            }

编写代码来监控亮度的变化.

Write the code to monitor the change in brightness.

然后你可以设置更新后的亮度如下:

then you can set the updated brightness as follows:

           //Set the system brightness using the brightness variable value
            Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
            //Get the current window attributes
            LayoutParams layoutpars = window.getAttributes();
            //Set the brightness of this window
            layoutpars.screenBrightness = brightness / (float)255;
            //Apply attribute changes to this window
            window.setAttributes(layoutpars);

清单中的权限:

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

API>=23,需要通过Settings Activity请求权限,描述如下:无法获得 WRITE_SETTINGS 权限

For API >= 23, you need to request the permission through Settings Activity, described here: Can't get WRITE_SETTINGS permission

这篇关于以编程方式更改系统亮度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆