以编程方式更改系统亮度

新手上路,请多包涵

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

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

因为我听说最大值是255。

但它什么都不做。请提出任何可以改变亮度的东西。谢谢

原文由 Usman Riaz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 542
2 个回答

您可以使用以下内容:

 // 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 中写:

 // 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();
}

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

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

 // 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 / 255f;
// Apply attribute changes to this window
window.setAttributes(layoutpars);

清单中的权限:

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

对于 API >= 23,您需要通过 Settings Activity 请求权限,描述如下: Can’t get WRITE_SETTINGS permission

原文由 Ritesh Gune 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以设置窗口的 screenBrightness 属性,如下所示:

 WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);

此代码/技术改编自 Almond Joseph Mendoza 于 2009 年 1 月 5 日发表的题为“以编程方式更改屏幕亮度”的博客条目( 存档在 Wayback Machine 上)。

screenBrightness 属性 是一个浮点值,范围从 0 到 1,其中 0.0 是 0% 亮度,0.5 是 50% 亮度,1.0 是 100% 亮度。

请注意,这不会影响整个系统的亮度,只会影响特定窗口的亮度。然而,在大多数情况下,对于大多数应用程序,这可能就是您所需要的。特别是,它具有不需要提升权限的优点,而提升权限是更改全局系统设置所必需的。

原文由 Amit Prajapati 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题