سؤال

I want my application to be connected to server though the mobile connection, yet allowing the device to go into sleep mode. I expect it to wake up when IP packates arrives.

How can this be done? How to receive "interrupts" from the Internet without draining battery?

هل كانت مفيدة؟

المحلول

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top