简体   繁体   中英

Android WakeLock not working on first run

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM