以编程方式更改系统亮度

Usm*_*iaz 43 java android brightness screen-brightness

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

WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = (255);
window.setAttributes(lp);
Run Code Online (Sandbox Code Playgroud)

因为我听说最大值是255.

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

Rit*_*une 49

您可以使用以下内容:

//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;
Run Code Online (Sandbox Code Playgroud)

在你的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();
            }
Run Code Online (Sandbox Code Playgroud)

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

然后您可以按如下方式设置更新的亮度:

           //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);
Run Code Online (Sandbox Code Playgroud)

清单中的权限:

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
Run Code Online (Sandbox Code Playgroud)

对于API> 23,您需要通过设置活动请求权限,如下所述: 无法获得WRITE_SETTINGS权限

  • 此解决方案不适用于我。我没有收到任何错误,但同时屏幕显示没有变化。 (2认同)

Bho*_*att 14

我有同样的问题.

两种解决方案

在这里,亮度= (int) 0 to 100 range因为我正在使用进度条

1解决方案

float brightness = brightness / (float)255;
WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = brightness;
        getWindow().setAttributes(lp);
Run Code Online (Sandbox Code Playgroud)

2解决方案

当我的进度条stop寻求时,我只是使用虚拟活动来打电话.

 Intent intent = new Intent(getBaseContext(), DummyBrightnessActivity.class);
                    Log.d("brightend", String.valueOf(brightness / (float)255));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //this is important
                    //in the next line 'brightness' should be a float number between 0.0 and 1.0
                    intent.putExtra("brightness value", brightness / (float)255); 
                    getApplication().startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

现在来到DummyBrightnessActivity.class

 public class DummyBrightnessActivity extends Activity{

private static final int DELAYED_MESSAGE = 1;

private Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);            
    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == DELAYED_MESSAGE) {
                DummyBrightnessActivity.this.finish();
            }
            super.handleMessage(msg);
        }
    };
    Intent brightnessIntent = this.getIntent();
    float brightness = brightnessIntent.getFloatExtra("brightness value", 0);
    WindowManager.LayoutParams lp = getWindow().getAttributes();
    lp.screenBrightness = brightness;
    getWindow().setAttributes(lp);

    Message message = handler.obtainMessage(DELAYED_MESSAGE);
    //this next line is very important, you need to finish your activity with slight delay
    handler.sendMessageDelayed(message,200); 
}

}
Run Code Online (Sandbox Code Playgroud)

不要忘记注册DummyBrightnessActivity来显示.

希望能帮助到你!!


Spi*_*pau 12

就我而言,我只想在显示 a 时点亮屏幕,Fragment不是更改系统范围的设置。有一种方法可以仅更改应用程序/活动/片段的亮度。我使用LifecycleObserver来调整屏幕亮度Fragment

class ScreenBrightnessLifecycleObserver(private val activity: WeakReference<Activity?>) :
    LifecycleObserver {

    private var defaultScreenBrightness = 0.5f

    init {
        activity.get()?.let {
            defaultScreenBrightness = it.window.attributes.screenBrightness
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun lightUp() {
        adjustScreenBrightness(1f)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun lightDown() {
        adjustScreenBrightness(defaultScreenBrightness)
    }

    private fun adjustScreenBrightness(brightness: Float) {
        activity.get()?.let {
            val attr = it.window.attributes
            attr.screenBrightness = brightness
            it.window.attributes = attr
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

LifecycleObserver在您的Fragment

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        // ...

        lifecycle.addObserver(ScreenBrightnessLifecycleObserver(WeakReference(activity)))

        // ...

        return binding.root
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个非常好的和优雅的解决方案! (2认同)

小智 10

我尝试了其他人发布的几个解决方案,但没有一个完全正确.geet的答案基本上是正确的,但有一些语法错误.我在我的应用程序中创建并使用了以下函数,它运行良好.请注意,这会根据原始问题中的要求特别更改系统亮度.

public void setBrightness(int brightness){

    //constrain the value of brightness
    if(brightness < 0)
        brightness = 0;
    else if(brightness > 255)
        brightness = 255;


    ContentResolver cResolver = this.getApplicationContext().getContentResolver();
    Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);

}
Run Code Online (Sandbox Code Playgroud)


Ami*_*ati 9

参考链接

  WindowManager.LayoutParams layout = getWindow().getAttributes();
 layout.screenBrightness = 1F;
  getWindow().setAttributes(layout);     
Run Code Online (Sandbox Code Playgroud)

  • 0 和 1。见 https://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#screenBrightness (2认同)

Hit*_*ahu 5

完整答案

我不想使用窗口管理器来设置亮度。我希望亮度反映在系统级别以及 UI 上。以上答案都不适合我。最后这种方法对我有用。

在 Android Manifest 中添加写入设置权限

  <uses-permission android:name="android.permission.WRITE_SETTINGS"
        tools:ignore="ProtectedPermissions"/>
Run Code Online (Sandbox Code Playgroud)

写入设置是受保护的设置,因此请求用户允许写入系统设置:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.System.canWrite(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        }
Run Code Online (Sandbox Code Playgroud)

现在您可以轻松设置亮度

            ContentResolver cResolver = getContentResolver();
            Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
Run Code Online (Sandbox Code Playgroud)

brighness 值应该在 0-255 的范围内,所以如果你有范围(0-max)的滑块,那么你可以标准化(0-255)范围内的值

private float normalize(float x, float inMin, float inMax, float outMin, float outMax) {
    float outRange = outMax - outMin;
    float inRange  = inMax - inMin;
  return (x - inMin) *outRange / inRange + outMin;
}
Run Code Online (Sandbox Code Playgroud)

最后,您现在可以将亮度从 0-255 范围更改为 0-100%,如下所示:

 float brightness = normalize(progress, 0, 100, 0.0f, 255.0f);
Run Code Online (Sandbox Code Playgroud)

希望它能节省您的时间。