我想以编程方式更改系统亮度。为此,我正在使用以下代码:
WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = (255);
window.setAttributes(lp);
因为我听说最大值是 255。
但它什么也没做。请建议任何可以改变亮度的东西。谢谢
我想以编程方式更改系统亮度。为此,我正在使用以下代码:
WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = (255);
window.setAttributes(lp);
因为我听说最大值是 255。
但它什么也没做。请建议任何可以改变亮度的东西。谢谢
您可以使用以下内容:
// 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 请求权限,此处描述: 无法获得 WRITE_SETTINGS 权限
我有同样的问题。
两种解决方案:
在这里,亮度 =(int) 0 to 100 range
因为我正在使用进度条
1 解决方案
float brightness = brightness / (float)255;
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = brightness;
getWindow().setAttributes(lp);
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);
现在来到 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);
}
}
不要忘记将 DummyBrightnessActivity 注册到清单。
希望能帮助到你!!
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);
就我而言,我只想在显示 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
}
}
}
并在你的添加LifecycleObserver
这样的Fragment
:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// ...
lifecycle.addObserver(ScreenBrightnessLifecycleObserver(WeakReference(activity)))
// ...
return binding.root
}
我尝试了其他人发布的几种解决方案,但没有一个完全正确。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);
}
我不想使用窗口管理器来设置亮度。我希望亮度反映在系统级别和 UI 上。以上答案都不适合我。最后,这种方法对我有用。
在 Android Manifest 中添加写入设置权限
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions"/>
写入设置是受保护的设置,因此请求用户允许写入系统设置:
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);
}
}
现在您可以轻松设置亮度
ContentResolver cResolver = getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
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;
}
最后,您现在可以将亮度从 0-255 范围更改为 0-100%,如下所示:
float brightness = normalize(progress, 0, 100, 0.0f, 255.0f);
希望它能节省您的时间。
这对我有用,直到 kitkat 4.4,但不适用于 android L
private void stopBrightness() {
Settings.System.putInt(this.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, 0);
}
最佳解决方案
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 0.5F;
getWindow().setAttributes(layout);
// 0.5 is %50
// 1 is %100
这是有关如何更改系统亮度的完整代码
private SeekBar brightbar;
//Variable to store brightness value
private int brightness;
//Content resolver used as a handle to the system's settings
private ContentResolver Conresolver;
//Window object, that will store a reference to the current window
private Window window;
/** Called when the activity is first created. */
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Instantiate seekbar object
brightbar = (SeekBar) findViewById(R.id.ChangeBright);
//Get the content resolver
Conresolver = getContentResolver();
//Get the current window
window = getWindow();
brightbar.setMax(255);
brightbar.setKeyProgressIncrement(1);
try {
brightness = System.getInt(Conresolver, System.SCREEN_BRIGHTNESS);
} catch (SettingNotFoundException e) {
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
brightbar.setProgress(brightness);
brightbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
System.putInt(Conresolver, System.SCREEN_BRIGHTNESS, brightness);
LayoutParams layoutpars = window.getAttributes();
layoutpars.screenBrightness = brightness / (float) 255;
window.setAttributes(layoutpars);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress <= 20) {
brightness = 20;
} else {
brightness = progress;
}
}
});
}
或者您可以查看本教程以获得完整的代码
快乐编码:)
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 10; // range from 0 - 255 as per docs
getWindow().setAttributes(params);
getWindow().addFlags(WindowManager.LayoutParams.FLAGS_CHANGED);
这对我有用。不需要虚拟活动。这仅适用于您当前的活动。
private SeekBar Brighness = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lcd_screen_setting);
initUI();
setBrightness();
}
private void setBrightness() {
Brighness.setMax(255);
float curBrightnessValue = 0;
try {
curBrightnessValue = android.provider.Settings.System.getInt(
getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
int screen_brightness = (int) curBrightnessValue;
Brighness.setProgress(screen_brightness);
Brighness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progresValue,
boolean fromUser) {
progress = progresValue;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Do something here,
// if you want to do anything at the start of
// touching the seekbar
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
progress);
}
});
}
initUI(){
Brighness = (SeekBar) findViewById(R.id.brightnessbar);
}
在清单中添加这个
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
progress);
请试试这个,它可以帮助你。对我来说工作得很好
根据我的经验
1st method.
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 75 / 100.0f;
getWindow().setAttributes(lp);
其中根据 1.0f.100f 的亮度值是最大亮度。
上面提到的代码会增加当前窗口的亮度。如果我们想增加整个android设备的亮度,这个代码是不够的,我们需要使用
2nd method.
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, 192);
其中 192 是从 1 到 255 的亮度值。使用第二种方法的主要问题是它会在 android 设备中以增加的形式显示亮度,但实际上它不会增加 android 设备的亮度。这是因为它需要一些刷新.
这就是为什么我通过同时使用这两个代码来找到解决方案的原因。
if(arg2==1)
{
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 75 / 100.0f;
getWindow().setAttributes(lp);
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, 192);
}
它对我有用
您需要创建变量:
私有 WindowManager.LayoutParams mParams;
然后覆盖此方法(以保存您以前的参数):
@Override
public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
mParams = params;
super.onWindowAttributesChanged(params);
}
比您希望更改屏幕亮度的地方(在应用程序上)只需使用:
mParams.screenBrightness = 0.01f; //use a value between 0.01f for low brightness and 1f for high brightness
getWindow().setAttributes(mParams);
在 api 版本 28 上测试。
只是在为 Android 10 研究这个,这仍然对我有用。但是需要在片段中获取调用 Activity 实例,这不是最佳的,因为我们现在只从 onAttach 获取上下文。将其设置为 -1.0f 将其设置为系统值(亮度设置滑块中的那个),0.0f 到 1.0f 将亮度值设置为从最小值到最大值在您闲暇时。
WindowManager.LayoutParams lp = myactivity.getWindow().getAttributes();
lp.screenBrightness = brightness;
myactivity.getWindow().setAttributes(lp);
myactivity.getWindow().addFlags(WindowManager.LayoutParams.FLAGS_CHANGED);
我正在使用这个 utils 类 适用于 Android 9
public class BrightnessUtil {
public static final int BRIGHTNESS_DEFAULT = 190;
public static final int BRIGHTNESS_MAX = 225;
public static final int BRIGHTNESS_MIN = 0;
public static boolean checkForSettingsPermission(Activity activity) {
if (isNotAllowedWriteSettings(activity)) {
startActivityToAllowWriteSettings(activity);
return false;
}
return true;
}
public static void stopAutoBrightness(Activity activity) {
if (!isNotAllowedWriteSettings(activity)) {
Settings.System.putInt(activity.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
}
public static void setBrightness(Activity activity, int brightness) {
if (!isNotAllowedWriteSettings(activity)) {
//constrain the value of brightness
if (brightness < BRIGHTNESS_MIN)
brightness = BRIGHTNESS_MIN;
else if (brightness > BRIGHTNESS_MAX)
brightness = BRIGHTNESS_MAX;
ContentResolver cResolver = activity.getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
}
}
private static void startActivityToAllowWriteSettings(Activity activity) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + activity.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
@SuppressLint("ObsoleteSdkInt")
private static boolean isNotAllowedWriteSettings(Activity activity) {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(activity);
}
}