How to Get an Android Wakelock to Work

Wake Lock doesn't work

WindowManager.LaoutParams.FLAG_KEEP_SCREEN_ON is not a valid flag/level for PowerManager.newWakeLock(). You most likely intended it to be:

PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP.

Wakelock not working on Android

I think you misunderstand what a Wakelock does. A wakelock keeps the device active (think CPU running) while your program holds it. Here are some things it doesn't do:

  • Control the lifecycle of any thread in your application process
  • Control the lifecycle of your application!!

In fact, Android is absolutely guaranteed to stop your application, eventually, no matter what you do. When that happens, you disconnect from the PowerManager and your wakelock is automatically released.

You might want the AlarmManager.

Wake Lock Release not working

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();

}
});

}


Related Topics



Leave a reply



Submit