以编程方式更改系统亮度

时间:2013-08-19 11:23:54

标签: java android brightness screen-brightness

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

WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = (255);
window.setAttributes(lp);

因为我听说最大值是255。

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

16 个答案:

答案 0 :(得分:41)

您可以使用以下内容:

//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&gt; 23,您需要通过Settings Activity请求权限,如下所述: Can't get WRITE_SETTINGS permission

答案 1 :(得分:14)

我遇到了同样的问题。

两种解决方案:

这里,亮度= (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以显示。

希望它有所帮助!!

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

}

答案 3 :(得分:8)

Reference link

  WindowManager.LayoutParams layout = getWindow().getAttributes();
 layout.screenBrightness = 1F;
  getWindow().setAttributes(layout);     

答案 4 :(得分:4)

这对我有效,直到kitkat 4.4但不在android L

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

答案 5 :(得分:3)

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

$filePath = "uploads/"

或者您可以查看此tutorial以获取完整的代码 快乐的编码:)

答案 6 :(得分:3)

就我而言,我只想在显示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
}

答案 7 :(得分:2)

私人SeekBar Brighness = null;

{{1}}

答案 8 :(得分:2)

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

android.provider.Settings.System.putInt(getContentResolver(),
                    android.provider.Settings.System.SCREEN_BRIGHTNESS,
                    progress);

答案 9 :(得分:1)

请试试这个,它可以帮到你。工作得很好

根据我的经验

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


                    }

它适合我

答案 10 :(得分:0)

WindowManager.LayoutParams params = getWindow().getAttributes();
    params.screenBrightness = 10; // range from 0 - 255 as per docs
    getWindow().setAttributes(params);
    getWindow().addFlags(WindowManager.LayoutParams.FLAGS_CHANGED);

这对我有用。不需要虚拟活动。这仅适用于您当前的活动。

答案 11 :(得分:0)

您需要创建变量:

私有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上进行了测试。

答案 12 :(得分:0)

只是针对Android 10进行了调查,在这里我仍然可以使用。但是,由于我们现在仅从onAttach获取上下文,因此需要将调用的Activity实例放在片段内部,而这并不是最佳选择。将其设置为-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);

答案 13 :(得分:0)

我正在使用这个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);
}

}

答案 14 :(得分:0)

完整答案

我不想使用“窗口管理器”来设置亮度。我希望其灵活性能够反映在系统级别以及UI上。上面的答案对我都不起作用。终于,这种方法对我有用。

在Android清单中添加写入设置权限

  <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-10滑块的范围更改为0-255

            float brightness = normalize(progress, 0, 10, 0.0f, 255.0f);

希望它可以节省您的时间。

答案 15 :(得分:0)

最佳解决方案

WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 0.5F ; getWindow().setAttributes(layout);

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