无法在Android中以编程方式应用系统屏幕亮度

我正在使用以下设置系统自动亮度模式和级别:

android.provider.Settings.System.putInt(y.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS_MODE, 0); android.provider.Settings.System.putInt(y.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, y.brightness1); 

我可以改变自动brighess打开和closures,并设置不同的级别。 设置似乎正确应用 – 我可以进入设置 – >显示 – >亮度,而且无论什么时候设置我设置实际显示正确。 但是,实际的屏幕不会改变其亮度。 如果我只是点击显示设置中的滑块,然后一切都得到应用。

我应该提到我正在运行一个主要活动的应用程序,并且这些设置已经在BroadcastReceiver中得到了应用。 我曾尝试创build一个虚拟活动,并testing了那里的东西,但得到了相同的结果。

好的,在这里find答案: 刷新窗口小部件的显示?

基本上,必须做一个透明的活动来处理亮度变化。 这篇文章中没有提到的是你必须这样做:

 Settings.System.putInt(y.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS_MODE, 0); Settings.System.putInt(y.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, brightnessLevel); 

然后做

 WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness = brightness; getWindow().setAttributes(lp); 

如果在应用更改后立即调用finish(),则亮度将永远不会发生变化,因为必须在应用亮度设置之前创build布局。 所以我最终创build了一个有300ms延迟的线程,然后调用finish()。

我正在做一些与我的应用程序中的屏幕亮度类似的东西,我通过WindowManager进行操作。 我使用下面的代码来获取当前的屏幕亮度(并保存以备后用)并将其设置为完整:

  WindowManager.LayoutParams lp = getWindow().getAttributes(); previousScreenBrightness = lp.screenBrightness; float brightness = 1; lp.screenBrightness = brightness; getWindow().setAttributes(lp); 

我在我的Activity.onResume()方法调用的Application类中创build了一个静态方法。

 MyApplication extends Application { ... public static void setBrightness(final Activity context) { // get the content resolver final ContentResolver cResolver = context.getContentResolver(); // get the current window final Window window = context.getWindow(); try { // get the current system brightness int brightnessLevel = System.getInt(cResolver,System.SCREEN_BRIGHTNESS); // get the current window attributes LayoutParams layoutpars = window.getAttributes(); // set the brightness of this window layoutpars.screenBrightness = brightnessLevel / (float) 255; // apply attribute changes to this window window.setAttributes(layoutpars); } catch (SettingNotFoundException e) { // throw an error cuz System.SCREEN_BRIGHTNESS couldn't be retrieved Log.e("Error", "Cannot access system brightness"); e.printStackTrace(); } } } MyActivity extends Activity { ... public void onResume() { super.onResume(); Log.d(TAG, "onResume()"); MyApplication.setBrightness(this); } } 

使用上面“ user496854 ”给出的答案
如果你正在采取最大screenBrightness = 255然后在做

WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness = brightness; getWindow().setAttributes(lp);
将screenBrightness除以255

WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness = brightness/(float)255; getWindow().setAttributes(lp);