很好的文章，就mobile 空socket 的耗电状态做了深入的分析.
Continuing our series on mobile apps and their effect on battery drain, I’ll pick up where the three guidelines in Wayne Lee’s last post left off, especially #3: “Know what your app is doing with the hardware and when it’s doing it.”
One common way that mobile apps use too much power is through hanging sockets –network connections that the app is no longer using, but which the server thinks are still alive because the app has not closed them. The subsequent query from the server results in needless battery drain.
Here’s more background on the problem and how you can deal with it.
“Wake up. It’s time to go to sleep.”
Applications often “forget” to close their socket after they are done with it. Then, after some amount of time without data activity, the server times the socket out and closes it.
Socket termination in TCP requires a four-way handshake, so the server has to send a FIN packet to the device, which usually takes the device from the low-power dormant state to the higher-power active state. The device goes idle for a bit, then back to dormant. It’s like waking somebody up to tell them that it’s time to go to sleep.
Look at the example in the diagram. The red (1) shows the device jumping from dormant to active mode to send and receive data normally for a few seconds. Once finished, the cellular radio drops to a power-saving idle mode (2) in case that it’s needed again. After about 15 seconds of inactivity, the radio goes dormant (3).
But the app has left the socket open (hanging). The server doesn’t like loose ends, so it sends its FIN packet to the device. This rouses the radio from dormant to active again (4), the same as if it were sending/receiving data for the app. Worse yet, the radio follows the normal curve back down to idle for another 15 seconds, wasting more power (5).
Begin to get the idea?
The phone has to bring up the radio for a simple, easily avoidable handshake because the server has asked the device for something that the app should have provided in the first place. If no other traffic moves between the device and the network, the connection is a complete waste of several hundred milliamperes.
Assuming that the app uses the network four times in an hour, the simple fix of having the app close the socket when finished can reduce network power consumption by about 20 percent, which would be the difference between eight and ten hours of standby power.
The lesson is: Program your app to close sockets when it has finished with them. Otherwise, the phone consumes power to bring up the radio for a needless handshake with the server.
So, to paraphrase Wayne, you need to know what your app is doing with the cellular radio, when it’s doing it and how to turn it off when the app no longer needs it.
Questions? Visit the Trepn Profiler Support Forum or let me know in the comments below.