Kenertj Kenertj - 22 days ago 7
Java Question

Button stop functioning after turning on and off once

App has an imagebutton which turn screen brightness on and off, but after turning clicking it on and off one time, the button is not working anymore. Does anyone have idea, what is wrong with the code?

import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;

public class ScreenFlashlight extends AppCompatActivity {
private static String tag;
private static final String TAG = tag ;
private boolean brightnessOnOff;
private ImageButton screenFlashOnOffButton;

public ScreenFlashlight() throws Settings.SettingNotFoundException {
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_flashlight);
screenFlashOnOffButton = (ImageButton) findViewById(R.id.flashOnOffButton);
brightnessOnOff = false;


}
public void screenFlashButtonClicked(View view) {

try {
if (brightnessOnOff) {

turnBrightnessOff();
Log.d(TAG, "screenFlashButtonClicked: ");
} else {
brightnessOnOff = true;
turnBrightnessOn();
Log.d(TAG, "screenFlashButtonClicked: ");
}
} catch (Exception e) {
e.printStackTrace();
}

}



private void turnBrightnessOn() {
try {
screenFlashOnOffButton.setImageResource(R.drawable.screenonbutton);
int currentBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
//Screen refresh to add brightness

WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = currentBrightness/ 100.0f;
getWindow().setAttributes(lp);


} catch (Exception e) {
e.printStackTrace();
}
}

private void turnBrightnessOff() {
try {
screenFlashOnOffButton.setImageResource(R.drawable.screenoffbutton);
int currentBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
//Refresh screen

WindowManager.LayoutParams lpp = getWindow().getAttributes();
lpp.screenBrightness = currentBrightness;
getWindow().setAttributes(lpp);
} catch (Exception e) {
e.printStackTrace();
}
}

Answer

You never set brightnessOnOff to false when the brightness is turned off, so it will have value true after you press the button the first time. So your code will enter the if block everytime. What you need to do is set brightnessOnOff to false when you turn off the brightness, and set it to true when you turn the brightness on again. Basically, you need to alternate brightnessOnOff between true and false for it to work correctly

Comments