20

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.

David
  • 7,028
  • 10
  • 48
  • 95

1 Answers1

6

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.

Yoni Gross
  • 816
  • 8
  • 16
  • But what i I get the wakelock in `OnCreate()` method? That's what I'm doing, but still getting the error. – Pitel Feb 16 '17 at 09:47
  • @Pitel, can you post your code? (although you might need to create a new question, since it's probably a related but different problem) – Yoni Gross Feb 16 '17 at 13:03
  • and you get the exact same error? "WakeLock finalized while still held"? is WifiLock releases ok? And is it something happens rarely, or all the time? – Yoni Gross Feb 16 '17 at 17:47
  • Yes, all the time. And the asserts passes, so I guess the lock is released. – Pitel Feb 17 '17 at 08:28