android – WakeLock finalized while still held error even though I'm releasing it-ThrowExceptions

Exception or error:

I have a service that should be run in the background. It starts when my app is open, and ends whenever my app is turned off by the user.

Whenever my app is in the background or when the screen is turned off, I still need the service running.

I achieved this with a WakeLock, but for some reason I get the error in the title.

This is concerning because I might be memory leaking the WakeLock (if I understand correctly).

I am able to trigger the error by restarting my app.

Here is the relevant code:

public class SomeService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        PowerManager manager = (PowerManager) getSystemService(POWER_SERVICE);

        mWakeLock = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG");

        if (!mWakeLock.isHeld()) mWakeLock.acquire();

        //Handle other processing

        return START_STICKY;
    }

    @Override
    public void onDestroy() {

        if (mWakeLock.isHeld()) mWakeLock.release();
        super.onDestroy();
    }

}

I’m perplexed because in my onDestroy() I release the WakeLock. I’m not sure what is triggering the error.

How to solve:

Service.onStartCommand() can be called several times before Service.onDestroy(), as they do not represent ‘opposite’ events/states (see docs). You may acquire several locks (and losing the reference to the previous acquired lock each time), but when you service is finished / app closes, you are releasing only the last one.

Leave a Reply

Your email address will not be published. Required fields are marked *