如何在“片段”中以编程方式更改屏幕亮度

时间:2019-06-17 07:15:11

标签: java android android-fragments

当我的应用程序中显示对话框片段时,我需要将亮度屏幕设置为最大级别。我的应用程序对Android SDK 23的支持最少,我试图在Dialog Fragment的onCreate()内设置亮度,如下所示:

WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
float brightness=1.0f;
lp.screenBrightness = brightness;
getActivity().getWindow().setAttributes(lp);

但是亮度屏幕仅改变一会儿。如何在打开对话框时将亮度屏幕设置为最大级别,如何在关闭片段对话框时再次将其重置?

1 个答案:

答案 0 :(得分:0)

尝试下面的代码

 //add below permission in your manifest file
  <uses-permission android:name="android.permission.WRITE_SETTINGS" />

// also ask setting permission at runtime
  if(Build.VERSION.SDK_INT>Build.VERSION_CODES.M) {
       boolean canWriteSettings = Settings.System.canWrite(this);
        if (!canWriteSettings) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
            startActivity(intent);
        }
    }


  //  finally use below method for set brightness
      public void setScreenBrightness(Context mContext,int brightnessValue){
    // Make sure brightness value between 0 to 255
    if(brightnessValue >= 0 && brightnessValue <= 255){
        Settings.System.putInt(
                mContext.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS,
                brightnessValue
        );
    }
}