Reputation: 4267
I have implemented wakelock in my app with below code:
PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,"MyWakelockTag");
wakeLock.acquire();
I want to prevent screen from going off when the user is in my app. The weird thing is , on first run of the application(right after install) it doesn't work and screen goes off, However after that if I close the application and run it again, wakelock works and prevents the app from going off.
I noticed that in the first time I get this error in my log:
WakeLock finalized while still held: MyWakelockTag
But in the next runs I don't get this error and everything works.
I don't get what causes this problem on the first run and I'll appreciate if someone can help me with this.
Thanks
Upvotes: 0
Views: 1207
Reputation: 4267
The error I was getting in the first run of the application was :
WakeLock finalized while still held: MyWakelockTag
The solution was to add this line in onDestroy :
if(wakeLock.isHeld()){
wakeLock.release();
}
Upvotes: 0
Reputation: 134
Ok I believe I found the problem.
The WakeLock is reference counted. That means that if a second acquire() happens it will just bump the reference count. Every call to acquire() needs to be protected by a call to isHeld() as in:
if ((keepScreenOn != null) && (keepScreenOn.isHeld() == false)) {
keepScreenOn.acquire();
}
I had assumed that acquire() on a lock I held did nothing so multiple acquire() calls caused the problem. Since the reference count is not zero the GC throws an error.
Upvotes: 0