1

我想做的是创建一个代码,以便当用户移动 SeekBar 时,它会改变手机的亮度(随着它的移动)并将其设置为手机的MAIN设置。我已经剪断了我认为是问题的部分代码..

public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {     
    android.provider.Settings.System.putInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS, progress);
}

如果您需要更多信息,请告诉我。它确实会改变亮度,但是您必须刷新屏幕-按下电源按钮并再次解锁-它才能工作,我想不出一种以编程方式执行此操作的方法

任何帮助或建议将不胜感激,谢谢:)

4

1 回答 1

2

您将需要 WindowManager 来帮助您更改亮度。我的英语不好,所以我写了一个这样的示例代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ScreenBrightnessSeekBar = (SeekBar)findViewById(R.id.seekBrightness);

    //Brightness is a float-point number between 0 and 1,But getProess() returns Int, so, we can setMax(100), and then we div 100 later.

    ScreenBrightnessSeekBar.setMax(100);  
    ScreenBrightnessSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {  

        public void onStopTrackingTouch(SeekBar seekBar) {}  

        public void onStartTrackingTouch(SeekBar seekBar) {}  

        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            setScreenBrightness((float)seekBar.getProgress()/100);
        }  
    });
}

private void setScreenBrightness(float b){

    //get window attributes and save in layoutParams
    WindowManager.LayoutParams layoutParams = getWindow().getAttributes();  
    layoutParams.screenBrightness = b;

    //display the new brightness
    getWindow().setAttributes(layoutParams);
}

//新代码:

    SeekBar screenBrightnessSeekBar;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    screenBrightnessSeekBar = (SeekBar)findViewById(R.id.seekBrightness);  
    screenBrightnessSeekBar.setMax(255);
    screenBrightnessSeekBar.setProgress((int) (android.provider.Settings.System.getInt(
            getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS, 255)));

    screenBrightnessSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {  
        public void onStopTrackingTouch(SeekBar seekBar) {}
        public void onStartTrackingTouch(SeekBar seekBar) {}  

        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                android.provider.Settings.System.putInt(getContentResolver(),
                        android.provider.Settings.System.SCREEN_BRIGHTNESS, progress);

                WindowManager.LayoutParams layoutParams = getWindow().getAttributes();  
                layoutParams.screenBrightness = (float)progress / 255;

                getWindow().setAttributes(layoutParams);
            }
        }
    });
}

您将需要在 AndroidManifest.xml 中获得此权限

    <uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
于 2012-10-18T01:49:49.447 回答