I have a rather odd problem. Lately i tried to use a wakelock in my application using the following code:
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
screenLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println("Clicked");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!locked)
setKeepScreenOn(WakeupLightActivity.this, true);
else setKeepScreenOn(WakeupLightActivity.this, false);
System.out.println("Screen will stay on");
}
});
}
public void setKeepScreenOn(Activity activity, boolean keepScreenOn) {
if(keepScreenOn) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.screenLock.acquire();
}
else {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
this.screenLock.release();
}
}
The wakelock works perfectly: 5 seconds after pressing the button (and locking my phone) the screen turns on. This test, however, was done while my phone was connected to my laptop for debugging using a USB cable.
Now comes the weird part. When I DON'T have my phone connected with the USB cable, the wakelock simply DOES NOT turn on the screen. The device I am using is an HTC desire. I have actually tested it on another HTC desire, which did the same thing. Next, i tried it on an HTC Desire HD. And guess what: It worked perfectly again! I am really confused about this and wondering if the problem is simply a flaw in my phone type, or if I am doing something wrong in my code. Is there anything I can do about it? It would be incredibly awkward if any potential customers with a malfunctioning phone type would encounter the same problem after having purchased my app.
Note that I also tried the application while charging my phone with the cable connected to a wall plug. This leads to the same problem as not having my phone connected at all. Both HTC Desires run the same Android version (2.2.2).
Apparently all of this occured simply because i was using the wrong flags. The problem was solved by creating the WakeLock with the following flags:
PowerManager.SCREEN_BRIGHT_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP