简体   繁体   English

通过安卓应用改变屏幕亮度

[英]changing screen brightness via android app

I have the same need like this , but I found the answer under that question aren't work.我有同样需要像这样,但我发现根据该问题的答案是不工作的。

I want to make buttons to change my screen brightness while my app is running.我想在我的应用程序运行时制作按钮来改变我的屏幕亮度。

I have found this code, but it doesn't work if I copy this code into my mainActivity directly.我找到了这段代码,但是如果我直接将这段代码复制到我的 mainActivity 中,它就不起作用了。

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

I use android studio and API level is 21 and I added user permission.我使用 android studio,API 级别为 21 ,我添加了用户权限。

This piece code is the nearest to my target, who can help me run this code?这段代码离我的目标最近,谁能帮我运行这段代码?

This worked for me:这对我有用:

In onCreate() method write this,onCreate()方法中写这个,

private int brightness;

try{
    Settings.System.putInt(getContentResolver(),
                           Settings.System.SCREEN_BRIGHTNESS_MODE,
                           Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);

    brightness = Settings.System.getInt(getContentResolver(), 
                               Settings.System.SCREEN_BRIGHTNESS);
}
catch(SettingNotFoundException e){
    Log.e("Error", "Cannot access system brightness");
    e.printStackTrace();
}

To update the brightness,要更新亮度,

Settings.System.putInt(getContentResolver(), System.SCREEN_BRIGHTNESS, brightness);
LayoutParams layoutpars = getWindow().getAttributes();
layoutpars.screenBrightness = brightness / (float)255;
getWindow().setAttributes(layoutpars);

Permission in manifest,清单中的许可,

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

If you read that question carefully you'll find that you need to refresh your activity and one possible solution to refresh your activity (as mentioned in that answer too) is to create a dummy activity, start it and that finish in in its onCreate() method.如果您仔细阅读该问题,您会发现您需要刷新您的活动,而刷新您的活动的一种可能解决方案(如该答案中所述)是创建一个虚拟活动,启动它并在其 onCreate( ) 方法。 you also need this permission in your manifest:您还需要在清单中获得此权限:

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

Window#mWindowAttributes screenBrightness 0 到 1 调节亮度从暗到全亮

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM