0

the original question I asked here

However, after I write the code below, no matter which button I click, the brightness of the screen didn't change.

I use Android Studio and API level 21 and use virtual machine Nexus 5 API 21 ×86 and I added user permission in manifest

I create a method to update the screen brightness

public void UpdateBrightness(float brightness)
{
    Settings.System.putFloat(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness);
    WindowManager.LayoutParams layoutParams=getWindow().getAttributes();
    layoutParams.screenBrightness = brightness;
    getWindow().setAttributes(layoutParams);
}

This is OnCreate method

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_screen);
    background = (LinearLayout)findViewById(R.id.background);

    change_dark = (Button)findViewById(R.id.dark);
    change_middle = (Button)findViewById(R.id.middle);
    change_bright = (Button)findViewById(R.id.bright);

    change_dark.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            UpdateBrightness((float)0);
        }
    });

    change_middle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            UpdateBrightness((float)0.5);
        }
    });

    change_bright.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            UpdateBrightness((float)1);
        }
    });

    try{
        Settings.System.putInt(getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);


        Settings.System.getFloat(getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS);
    }
    catch(Settings.SettingNotFoundException e){
        Log.e("Error", "Cannot access system brightness");
        e.printStackTrace();
    }
}

I don't know why the brightness of the screen didn't change when I press the button, who can find something?

Community
  • 1
  • 1
Peter Zhu
  • 1,154
  • 3
  • 15
  • 27
  • Try writing `getApplicationContext().getContentResolver()` instead of `getContentResolver()`. Everything else looks okay – Apurva Feb 28 '15 at 10:32
  • @Apurva Pity that I tried until then but it still not work. I added a logcat to ensure the UpdateBrightness Method is called. Maybe it cannot work on a virtual machine? – Peter Zhu Feb 28 '15 at 10:51
  • test in real device, you'll see the change. Emulator will override your computer's brightness so it's not gonna show you result. – Apurva Feb 28 '15 at 10:56
  • Answer I wrote is exactly what I used in my previous project. So there's nothing to mail you. – Apurva Feb 28 '15 at 10:58

0 Answers0