Как настроить яркость устройства программно с помощью SeekBar?

У меня есть две панели поиска в моем приложении настроек, одна для звука и одна для яркости. Моя звуковая панель поиска изменяет громкость мультимедиа, как я этого хочу, и она остается измененной в других действиях и приложениях, но панель поиска яркости не остается измененной после того, как я изменяю действие, она только меняет яркость на странице настроек. Чего я хочу добиться, так это того, чтобы они оба оставались такими, какие я установил на странице настроек приложения, даже в других действиях и приложениях.

ApplicationSettings.java

public class ApplicationSettings extends AppCompatActivity {

private SeekBar VolumeSeekbar = null;
private SeekBar BrightnessSeekbar = null;
private AudioManager audioManager = null;
private float BackLightValue;
//Seek bar object
private SeekBar seekBar;
//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;
TextView txtPerc;



@Override
public void onCreate(Bundle savedInstanceState) {
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_application_settings);

    //Instantiate seekbar object
    seekBar = (SeekBar) findViewById(R.id.BrightBar);
    txtPerc = (TextView) findViewById(R.id.txtPercentage);
    //Get the content resolver
    cResolver =  getContentResolver();
    //Get the current window
    window = getWindow();

    VolumeControl();
    BrightnessControl();
}


public void GoToMainScreenButton1 (View view) {
    Intent intentStart = new Intent(this, MainScreen.class);
    startActivity(intentStart);
}

private void VolumeControl() {
    try {
        VolumeSeekbar = (SeekBar) findViewById(R.id.SoundBar);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        VolumeSeekbar.setMax(audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        VolumeSeekbar.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC));
        VolumeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
            }
            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
            }
            @Override
            public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        progress, 0);
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

}

private void BrightnessControl() {
    //Set the seekbar range between 0 and 255
    //seek bar settings//
    //sets the range between 0 and 255
    seekBar = (SeekBar) findViewById(R.id.BrightBar);

    seekBar.setMax(255);
    //set the seek bar progress to 1
    seekBar.setKeyProgressIncrement(1);

    try
    {
        //Get the current system brightness
        brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS);
    }
    catch (Settings.SettingNotFoundException e)
    {
        //Throw an error case it couldn't be retrieved
        Log.e("Error", "Cannot access system brightness");
        e.printStackTrace();
    }

    //Set the progress of the seek bar based on the system's brightness
    seekBar.setProgress(brightness);

    //Register OnSeekBarChangeListener, so it can actually change values
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
    {
        public void onStopTrackingTouch(SeekBar seekBar)
        {
            //Set the system brightness using the brightness variable value
            Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
            //Get the current window attributes
            WindowManager.LayoutParams layoutpars = window.getAttributes();
            //Set the brightness of this window
            layoutpars.screenBrightness = brightness / (float)255;
            //Apply attribute changes to this window
            window.setAttributes(layoutpars);
        }
        public void onStartTrackingTouch(SeekBar seekBar)
        {
            //Nothing handled here
        }
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
        {
            //Set the minimal brightness level
            //if seek bar is 20 or any value below
            if(progress<=20)
            {
                //Set the brightness to 20
                brightness=20;
            }
            else //brightness is greater than 20
            {
                //Set brightness variable based on the progress bar
                brightness = progress;
            }
            //Calculate the brightness percentage
            float perc = (brightness /(float)255)*100;
            //Set the brightness percentage
            txtPerc.setText((int)perc +" %");
        }
    });
}
}

Activity_application_settings.xml

<!--        android:background="#000000"-->

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=" Adjust the Sound volume"
    android:id="@+id/SOUNDTEXT"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginTop="87dp" />

<SeekBar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/SoundBar"
    android:background="#87CEEB"
    android:layout_gravity="center_vertical"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/SOUNDTEXT"
    android:layout_alignRight="@+id/Mainbutton11"
    android:layout_alignEnd="@+id/Mainbutton11" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=""
    android:id="@+id/SoundPercentage"
    android:background="#87CEEB"
    android:layout_alignBottom="@+id/SoundBar"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@+id/SoundBar"
    android:layout_toEndOf="@+id/SoundBar" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=" Adjust the Brightness"
    android:id="@+id/textView18"
    android:layout_above="@+id/BrightBar"
    android:layout_toStartOf="@+id/Mainbutton11"
    android:layout_toLeftOf="@+id/Mainbutton11"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<SeekBar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/BrightBar"
    android:background="#87CEEB"
    android:layout_gravity="left|bottom"
    android:layout_centerVertical="true"
    android:layout_toLeftOf="@+id/SoundPercentage"
    android:layout_toStartOf="@+id/SoundPercentage" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/txtPercentage"
    android:layout_alignTop="@+id/BrightBar"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignLeft="@+id/SoundPercentage"
    android:layout_alignStart="@+id/SoundPercentage" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Go to chapters"
    android:background="#FFE4B5"
    android:onClick="GoToMainScreenButton1"
    android:id="@+id/Mainbutton11"
    android:layout_gravity="center_horizontal|top"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />


person GChanna    schedule 23.04.2016    source источник


Ответы (1)


Вы работаете с автоматическим режимом яркости?

Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);

Также у вас есть разрешение на манифест?

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

PS: я бы прокомментировал эти вопросы, но пока не могу комментировать, извините.

person Community    schedule 23.04.2016
comment
настройки записи уже есть в моем манифесте, сейчас проверю ручной режим, ура. - person GChanna; 23.04.2016