Quadroid
Quadroid

Reputation: 237

Can I get rid of WakeLock?

My app has a couple of services running in the background. They use: a long lived TCP connection, GPS, Accelerometer and android.os.CountDownTimer.

I already know the Accelerometer and CountDownTimer require a partial WakeLock to work when my phone goes to sleep (Android 2.2), GPS doesn't require a WakeLock, not sure about TCP sockets?

CountDownTimer hopefully can be replaced by java.util.Timer which I think will still work without a WakeLock? Then I can acquire/release the WakeLock for periodic Accelerometer checks. Then when the Acclerometer detects movement I can turn on the GPS. And if there is no GPS signal I can go back to my timer full circle.

Will this work without a permanent WakeLock? I don't know about the TCP connection.

EDIT: Turns out you have to use an AlarmManager in deep sleep when no wakelock is set to get accurate timers.

The TCP socket works well enough without a wakelock:

http://devtcg.blogspot.com/2009/01/push-services-implementing-persistent.html

Some sample code, which tries to keep the socket alive:

http://code.google.com/p/android-random/source/browse/#svn/trunk/TestKeepAlive

If you don't use setSoTimeout (or set to 0 for infinite) the socket seems to last a long time even without doing anything to keep it alive when the phone is sleeping. Although I am acquiring and releasing a WakeLock every minute in another service. I'm not sure what effect that has (if any) on the TCP socket.

Upvotes: 0

Views: 1138

Answers (1)

Tomasz W
Tomasz W

Reputation: 2076

You may want to consider using SoLinger flag to keep your socket 'alive' when it's expected to close. I believe SSH uses this mechanism to keep your connection 'ready' for some time even if you lose physical connectivity. You will want to set this flag on both ends.

there is also something you need to be aware of: if your linger timeout is large (say - an hour), you lose connectivity, you will want to set linger timeout to 0 before you call close() on it. otherwise you'll have to wait for the socket to flush data (either due to timeout or connection re-establishment)

Upvotes: 1

Related Questions