How to make the Android device hold a TCP connection to Internet without wake lock?

好久不见. 提交于 2019-11-28 04:25:30

When you are blocked on a read from a tcp stream the device can go into a deep sleep and when tcp traffic comes in it will briefly wakeup the device, as soon as a bit is read in you start a wakelock until you have received the whole transmission then release it.

Here is an example with web sockets, I've ran this app for over 12 hours in the background with no battery impact. https://github.com/schwiz/android-websocket-example

The client is here, the blocking read is in the start method. https://github.com/schwiz/android-websockets/blob/master/src/com/codebutler/android_websockets/HybiParser.java

I've been using long living TCP connections on Android without a wake lock for some years now.

My experience is that when data arrives on a TCP connection and the device is in deep sleep, it will be woken up for a short period of time at least. Waking up the device could take up to ~2 minutes sometimes, but it's usually done within a few seconds.

Now that the device is awake, the receiving process has some time too process the data. Now either the process is able to do so before the device is put back into deep sleep, or the device will be put into deep sleep suspending also the process. The important thing here is that the data is not lost, it remains in the memory and the process is able to resume the work processing the data the next time the device leaves deep sleep. Of course, this means that if the sender awaits an answer to his data, it may take some time, until he gets it.

You could take a wake lock as soon as your network library notifies you that a new message was received. But if you done, then make sure to handle the lock properly, i.e. ensure that it is released at some point and in every code path. I personally never experienced the need for a wake lock, the Android device was always long enough awake to process the request. But your millage may vary.

Google Cloud Messaging might be what you are looking for:

http://developer.android.com/guide/google/gcm/index.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!