Android socket in the system hibernation case research

Source: Internet
Author: User

Do 3 years of IM application, has not confirmed that the socket in the system hibernation situation will not receive the message, the Internet also searched some information said Android phone is divided into AP and BP two parts, the system sleep when the AP is dormant, and BP is not dormant, network protocol stack is running in the BP layer , so when the BP receives the packet, the system wakes up the AP, but the AP runs at a very short time. Although it sounds reasonable, but did not personally tested, or a heart attack ~ ~ ~, today, think of this matter, simply write your own code test to see the results.

Server端code:
 Public  class testserver {     Public Static void Main(string[] argv) {ServerSocket serversocket;Try{ServerSocket =NewServerSocket (4444); Socket client; while(client = Serversocket.accept ())! =NULL) {NewClientthread (client). Start (); }        }Catch(IOException e)        {E.printstacktrace (); }    } Public Static  class clientthread extends Thread {        PrivateSocket socket;PrivateOutputStream OutputStream; Public Clientthread(Socket client) {socket = client;Try{outputstream = Socket.getoutputstream (); }Catch(IOException e)            {E.printstacktrace (); }        } Public void Run() {intindex =0; while(true) {Try{Outputstream.write ("Hello"+index+"\ n"). GetBytes ());                    index++; System.out.println ("Send"); }Catch(IOException e)                {E.printstacktrace (); }Try{Thread.Sleep ( -* +); }Catch(Interruptedexception e)                {E.printstacktrace (); }            }        }    }}

The code is simple, and the server sends a Hello and index number to the client every 60s.

Client-side code:

 Public  class testactivity extends Activity {    PrivateFileOutputStream OutputStream =NULL;PrivateWakeLock Mwakelock;PrivateHandler Handler =NewHandler () { Public void Handlemessage(Message msg) {Try{Outputstream.write (NewDate (). ToString () + ((String) msg.obj) +"Savelocal\n"). GetBytes ()); }Catch(IOException e)            {E.printstacktrace (); }//Releasewakelock ();}    };protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.main);NewThread (NewRunnable () {@Override             Public void Run() {File File =NewFile ("/sdcard/testlog-lock.txt");if(File.exists ())                {File.delete (); }Try{File.createnewfile (); }Catch(IOException E2)                {E2.printstacktrace (); }Try{OutputStream =NewFileOutputStream (file); }Catch(FileNotFoundException E2)                {E2.printstacktrace (); }Try{Socket socket =NewSocket (); Socket.connect (NewInetsocketaddress ("10.140.82.31",4444));                    InputStream InputStream = Socket.getinputstream (); BufferedReader inputStream2 =NewBufferedReader (NewInputStreamReader (InputStream)); String lineString; while((lineString = Inputstream2.readline ())! =NULL) {//Acquirewakelock ();Outputstream.write ((NewDate (). toString () + lineString +"receive\n"). GetBytes ()); Message msgmessage = Handler.obtainmessage (1, lineString); Handler.sendmessagedelayed (Msgmessage, the); }                }Catch(Unknownhostexception e) {Try{Outputstream.write (E.getmessage (). GetBytes ()); }Catch(IOException E1)                    {E1.printstacktrace (); }                }Catch(IOException e) {Try{Outputstream.write (E.getmessage (). GetBytes ()); }Catch(IOException E1)                    {E1.printstacktrace ();    }}}). Start (); }Private void Acquirewakelock() {if(Mwakelock = =NULL) {PowerManager PowerManager = (powermanager) getsystemservice (Context.power_service); Mwakelock = Powermanager.newwakelock (Powermanager.partial_wake_lock,"Lock");    } mwakelock.acquire (); }Private void Releasewakelock() {if(Mwakelock! =NULL&& Mwakelock.isheld ()) {mwakelock.release (); } Mwakelock =NULL; }}

The code is not complex, when the client starts, it creates a thread to connect to the server, writes the received content and timestamp to the file every time a packet is received, and then writes the same content and timestamp to the file again after 5s. Why do you want 5s? Because I want to verify that the socket read to the package, is not running a moment immediately after sleep, if yes, then 5s, the 2nd time is not written to the file on time, because the system is dormant, the program will not be executed, handler inside the message can not be executed. The important place is the sentence acquirewakelock and Releasewakelock, if Wake, then the 2nd write must be completed within 5s.

    所以我们注释wakelock和打开wakelock测试两次,验证3件事情:

1. The system will not be able to receive packets after hibernation,
2. After receiving the packet, comment wakelock, what is the behavior,
3. Open Wakelock, what is the behavior.

Note that when testing to disconnect the USB, because the phone is not dormant when attached to the USB, then run the app, put the app in the background off the phone screen, test for half an hour, see log to verify the conjecture.
Here is the log for the next client of the test,

1. 不加wakelock

1 Mon Jul 22:37:16 CDT 2015hello0 receive
2 Mon Jul 22:37:21 CDT 2015hello0 savelocal
3 Mon Jul 20 22:3 8:15 CDT 2015hello1 Receive
4 Mon Jul 22:39:15 CDT 2015hello2 receive
5 Mon Jul 22:40:15 CDT 2015hello3 re Ceive
6 Mon Jul 22:40:15 CDT 2015hello1 savelocal
7 Mon Jul 22:41:15 CDT 2015hello4 receive
8 Mon Jul 22:42:15 CDT 2015HELLO5 Receive
9 Mon Jul 22:42:15 CDT 2015hello2 savelocal
Mon Jul 22:43:15 CDT 20 15hello6 receive
Mon Jul 22:43:15 cdt 2015hello3 savelocal
Mon Jul 22:44:15 CDT 2015hello7 Receive br> Mon Jul 22:45:15 CDT 2015hello8 receive
Mon Jul 22:46:15 cdt 2015hello4 savelocal
Mon Jul 20 22:47:15 CDT 2015hello10 receive
Mon Jul 22:48:15 CDT 2015hello11 receive
+ Mon Jul 22:48:15 CDT 2015h Ello5 savelocal
Mon Jul 22:49:15 CDT 2015hello12 receive
Mon Jul 22:49:15 CDT 2015hello6 savelocal

Here only a portion of the log, you can see that the packets are received at each 60s interval, but the 5s after the save message code is not executed according to the frequency of 5s, but wait until the subsequent packet received, the program was awakened a bit, caught a execution gap execution.

    1. Add Wakelock

1 Mon Jul 23:27:37 CDT 2015hello0 receive
2 Mon Jul 23:27:42 CDT 2015hello0 savelocal
3 Mon Jul 23:28:37 CDT 2015hello1 receive
4 Mon Jul 23:28:42 CDT 2015hello1 savelocal
5 Mon Jul 23:29:37 CDT 2015hello2 receive
6 Mon Jul 23:29:42 CDT 2015hello2 savelocal
7 Mon Jul 23:30:37 CDT 2015hello3 receive
8 Mon Jul 23:30:42 CDT 2015hello3 savelocal
9 Mon Jul 23:31:37 CDT 2015hello4 receive
Ten Mon Jul 23:31:42 CDT 2015hello4 savelocal
Mon Jul 23:32:37 CDT 2015hello5 receive
Mon Jul 23:32:42 CDT 2015hello5 savelocal
Mon Jul 23:33:37 CDT 2015hello6 receive
Mon Jul 23:33:42 CDT 2015hello6 savelocal
Mon Jul 23:34:37 CDT 2015hello7 receive

You can see that the code for save is guaranteed to run after a 5s delay.

OK, Conclusion:
1. In the case of system hibernation, the socket is able to receive the package on time
2. After receiving the package, the program will immediately hibernate again, follow up to execute a long period of code, it is best to obtain the wakelock to ensure that the code can be executed, and then release Wakelock. This is actually very much like Broadcastreceiver, the system will automatically help us get the wakelock during the OnReceive function execution, the function will release the Wakelock, so if you want to execute a long time code, Then you have to get it yourself and release wakelock, or the framework has a name that Wakefulbroadcastreceiver did for us.

Note: I only tested WiFi in the case, that BP seems to just refer to radio and WiFi chip is not a thing, but the feeling with 3g of the case should be almost ~ ~ ~ Try it sometime

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android socket in the system hibernation case research

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.