Java 以编程方式更改系统亮度

Java 以编程方式更改系统亮度,java,android,brightness,screen-brightness,Java,Android,Brightness,Screen Brightness,我想以编程方式更改系统亮度。为此,我使用以下代码: WindowManager.LayoutParams lp = window.getAttributes(); lp.screenBrightness = (255); window.setAttributes(lp); 因为我听说最大值是255 但它什么也没做。请建议任何可以改变亮度的东西。 谢谢 我也有同样的问题 两种解决方案: 这里,亮度=(int)0到100范围,因为我正在使用progressbar 1个解决方案 float brig

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

WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = (255);
window.setAttributes(lp);
因为我听说最大值是255

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


我也有同样的问题

两种解决方案:

这里,亮度=
(int)0到100范围
,因为我正在使用progressbar

1个解决方案

float brightness = brightness / (float)255;
WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = brightness;
        getWindow().setAttributes(lp);
2解决方案

float brightness = brightness / (float)255;
WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = brightness;
        getWindow().setAttributes(lp);
当我的进度条
停止
搜索时,我只是使用虚拟活动来调用

 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以显示


希望能有帮助

您可以使用以下命令:

//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 / (float)255;
            //Apply attribute changes to this window
            window.setAttributes(layoutpars);
清单中的权限:

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

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

请试试这个,它可能对你有帮助。对我来说很好

根据我的经验

 1st method.
                     WindowManager.LayoutParams lp = getWindow().getAttributes();  
                 lp.screenBrightness = 75 / 100.0f;  
                 getWindow().setAttributes(lp);
其中,亮度值非常符合1.0f.100f,即最大亮度

上述代码将增加当前窗口的亮度。如果我们想增加整个安卓设备的亮度,这段代码是不够的,我们需要使用它

   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);


                    }

它对我来说运行正常

我尝试了其他人发布的几种解决方案,但没有一种完全正确。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);

}
public亮度(整数亮度){
//约束亮度的值
如果(亮度<0)
亮度=0;
否则如果(亮度>255)
亮度=255;
ContentResolver cResolver=this.getApplicationContext().getContentResolver();
Settings.System.putInt(cResolver,Settings.System.SCREEN\u亮度,亮度);
}

这在kitkat 4.4之前对我有效,但在android L中不起作用

private void stopBrightness() {
    Settings.System.putInt(this.getContentResolver(),
            Settings.System.SCREEN_BRIGHTNESS, 0);
}

这是关于如何更改系统亮度的完整代码

    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;
                }
            }
        });
    }
private SeekBar-brightbar;
//用于存储亮度值的变量
亮度;
//用作系统设置句柄的内容解析程序
私有内容解析器Conresolver;
//窗口对象,该对象将存储对当前窗口的引用
私人窗口;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//实例化seekbar对象
brightbar=(SeekBar)findViewById(R.id.ChangeBright);
//获取内容解析器
Conresolver=getContentResolver();
//获取当前窗口
window=getWindow();
设置最大值(255);
brightbar.setKeyProgressIncrement(1);
试一试{
亮度=System.getInt(Conresolver,System.SCREEN\u亮度);
}捕获(设置NotFound异常e){
Log.e(“错误”,“无法访问系统亮度”);
e、 printStackTrace();
}
设置进度(亮度);
setOnSeekBarChangeListener(新的OnSeekBarChangeListener(){
TopTrackingTouch(SeekBar SeekBar)上的公共无效{
System.Putin(Conresolver,System.SCREEN_亮度,亮度);
LayoutParams layoutpars=window.getAttributes();
layoutpars.screenBrightness=亮度/(浮动)255;
设置属性(layoutpars);
}
开始跟踪触摸时的公共无效(SeekBar SeekBar){
}
public void onProgressChanged(SeekBar-SeekBar、int-progress、boolean-fromUser){
如果(进展)
将此添加到清单中

<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);
android.provider.Settings.System.putInt(getContentResolver(), android.provider.Settings.System.SCREEN_亮度, 进展);
您需要创建变量:

私有WindowManager.LayoutParams mParams

然后重写此方法(以保存以前的参数):

如果您希望更改屏幕亮度(在应用程序上),只需使用:

    mParams.screenBrightness = 0.01f; //use a value between 0.01f for low brightness and 1f for high brightness
    getWindow().setAttributes(mParams);

在api版本28上测试。

在我的情况下,我只想在显示
片段时点亮屏幕,而不更改系统范围的设置。有一种方法只能更改应用程序/活动/片段的亮度。我使用a来调整一个
片段的屏幕亮度:

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
        }
    }
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        // ...

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

        // ...

        return binding.root
}

我刚刚在Android 10上研究过这一点,但这仍然适用于我。但是需要在片段中获取调用活动实例,这不是最佳的,因为我们现在只从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类BrightnessUtil{
公共静态最终整数亮度\u默认值=190;
公共静态最终整数亮度_MAX=225;
公共静态最终整数亮度_MIN=0;
设置权限的公共静态布尔检查(
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
        }
    }
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        // ...

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

        // ...

        return binding.root
}
    WindowManager.LayoutParams lp = myactivity.getWindow().getAttributes();
    lp.screenBrightness = brightness;
    myactivity.getWindow().setAttributes(lp);
    myactivity.getWindow().addFlags(WindowManager.LayoutParams.FLAGS_CHANGED);
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);
}
  <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);
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;
}
 float brightness = normalize(progress, 0, 100, 0.0f, 255.0f);
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 0.5F ; getWindow().setAttributes(layout);

// 0.5 is %50
// 1 is %100