I have to make an app that keeps the screen on using a wake lock. I have two buttons, one to turn the wake lock on and one to turn it off.
The button to turn on the wake lock works fine, but the button to turn off the wake lock causes the app to crash when it is pressed.
Here's the code:
public class MainActivity extends ActionBarActivity {
@Override @SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupScreenONButton();
setupScreenOFFButton();
}
@SuppressWarnings("deprecation")
private void setupScreenOFFButton() {
Button ScreenOffButton = (Button) findViewById(R.id.buttonScreenOFF);
ScreenOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"Screen OFF");
wl.release();
Toast.makeText(MainActivity.this, "Screen OFF", Toast.LENGTH_SHORT).show();
}
});
}
@SuppressWarnings("deprecation")
private void setupScreenONButton() {
Button ScreenOnButton = (Button) findViewById(R.id.buttonScreenON);
ScreenOnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,"Screen ON");
wl.acquire();
Toast.makeText(MainActivity.this,"Screen ON", Toast.LENGTH_SHORT).show();
}
});
}
Any ideas on what I'm doing wrong? Thanks
You need to release the same Wakelock, that was acquired before, not get a new one.
Edit: Added code (untested):
public class MainActivity extends ActionBarActivity {
PowerManager.WakeLock wl;
@Override @SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"Screen OFF");
setContentView(R.layout.activity_main);
setupScreenONButton();
setupScreenOFFButton();
}
@SuppressWarnings("deprecation")
private void setupScreenOFFButton() {
Button ScreenOffButton = (Button) findViewById(R.id.buttonScreenOFF);
ScreenOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
wl.release();
Toast.makeText(MainActivity.this, "Screen OFF", Toast.LENGTH_SHORT).show();
}
});
}
@SuppressWarnings("deprecation")
private void setupScreenONButton() {
Button ScreenOnButton = (Button) findViewById(R.id.buttonScreenON);
ScreenOnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
wl.acquire();
Toast.makeText(MainActivity.this,"Screen ON", Toast.LENGTH_SHORT).show();
}
});
}