Investigation on Android socket sleep

Source: Internet
Author: User

Investigation on Android socket sleep

After three years of IM application, I have never confirmed whether the socket will not receive messages when the system is sleeping, some materials have been searched on the internet, saying that android phones are divided into AP and BP. When the system is sleeping, AP is sleeping, while BP is not sleeping, the network protocol stack runs on the BP layer, so when the BP receives the data packet, the system will wake up the AP, but the AP runs for a short time. Although it sounds quite reasonable, it's still a heart disease that has not been tested by yourself ~~~, Today, I think of this again. I just want to write code and test the results by myself.

Server code:
public class TestServer {    public static void main(String[] argv) {        ServerSocket serverSocket;        try {            serverSocket = new ServerSocket(4444);            Socket client;            while((client = serverSocket.accept()) != null) {                new ClientThread(client).start();            }        } catch (IOException e) {            e.printStackTrace();        }    }    public static class ClientThread extends Thread {        private Socket socket;        private OutputStream outputStream;        public ClientThread(Socket client) {            socket = client;            try {                outputStream = socket.getOutputStream();            } catch (IOException e) {                e.printStackTrace();            }        }        public void run() {            int index = 0;            while(true) {                try {                                        outputStream.write((hello+index+).getBytes());                    index++;                    System.out.println(send);                } catch (IOException e) {                    e.printStackTrace();                }                try {                    Thread.sleep(60*1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }}

The code is very simple. The Server sends a hello and index number to the client every 60 s.

Client code:

public class TestActivity extends Activity {    private FileOutputStream outputStream = null;    private WakeLock mWakelock;    private Handler handler = new Handler() {        public void handleMessage(Message msg) {            try {                outputStream.write((new Date().toString() + ((String) msg.obj) +   savelocal)                        .getBytes());            } catch (IOException e) {                e.printStackTrace();            }//            releaseWakeLock();        }    };    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        new Thread(new Runnable() {            @Override            public void run() {                File file = new File(/sdcard/testlog-lock.txt);                if (file.exists()) {                    file.delete();                }                try {                    file.createNewFile();                } catch (IOException e2) {                    e2.printStackTrace();                }                try {                    outputStream = new FileOutputStream(file);                } catch (FileNotFoundException e2) {                    e2.printStackTrace();                }                try {                    Socket socket = new Socket();                    socket.connect(new InetSocketAddress(10.140.82.31, 4444));                    InputStream inputStream = socket.getInputStream();                    BufferedReader inputStream2 = new BufferedReader(new InputStreamReader(                            inputStream));                    String lineString;                    while ((lineString = inputStream2.readLine()) != null) {//                        acquireWakeLock();                        outputStream.write((new Date().toString() + lineString +  receive)                                .getBytes());                        Message msgMessage = handler.obtainMessage(1, lineString);                        handler.sendMessageDelayed(msgMessage, 5000);                    }                } 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, a Thread is established to connect to the Server. Each packet is received, the received content and timestamp are immediately written into the file, after five seconds, write the same content and timestamp to the file again. Why 5s? Because I want to verify that after the socket reads the package, it will immediately sleep after it runs for a while. If yes, it will not write files on time for 2nd times after 5s, because the system is sleeping, the program will not be executed, and the Message in Handler will not be executed. The most important thing is the sentence acquireWakelock and releaseWakelock. If it is done by a wake, 2nd write operations must be completed within 5s.

So we commented on the wakelock and opened the wakelock test twice to verify three things:

1. Can I still receive the package after the system sleep,
2. After receiving the package, comment out what the wakelock is,
3. Open wakelock.

Note that you need to disconnect the usb during the test, because the mobile phone will not sleep when connected to the usb, and then run the App to put the App in the background to close the mobile phone screen, respectively for a test for half an hour, check the log to verify the conjecture.
The following is the log of the next Client,

1. Do not add wakelock

1 Mon Jul 20 22:37:16 CDT 2015hello0 receive
2 monjul 20 22:37:21 CDT 2015hello0 savelocal
3 Mon Jul 20 22:38:15 CDT 2015hello1 receive
4 monjul 20 22:39:15 CDT 2015hello2 receive
5 monjul 20 22:40:15 CDT 2015hello3 receive
6 monjul 20 22:40:15 CDT 2015hello1 savelocal
7 Mon Jul 20 22:41:15 CDT 2015hello4 receive
8 monjul 20 22:42:15 CDT 2015hello5 receive
9 Mon Jul 20 22:42:15 CDT 2015hello2 savelocal
10 monjul 20 22:43:15 CDT 2015hello6 receive
11 monjul 20 22:43:15 CDT 2015hello3 savelocal
12 monjul 20 22:44:15 CDT 2015hello7 receive
13 Mon Jul 20 22:45:15 CDT 2015hello8 receive
14 Mon Jul 20 22:46:15 CDT 2015hello4 savelocal
15 Mon Jul 20 22:47:15 CDT 2015hello10 receive
16 monjul 20 22:48:15 CDT 2015hello11 receive
17 Mon Jul 20 22:48:15 CDT 2015hello5 savelocal
18 Mon Jul 20 22:49:15 CDT 2015hello12 receive
19 Mon Jul 20 22:49:15 CDT 2015hello6 savelocal

Only some logs are pasted here. We can see that the data packets are received at an interval of 60 s, but the Message code saved after 5s is not executed at the frequency of 5s, instead, after receiving the package, the program was awakened and the execution gap was caught.

Add wakelock

1 Mon Jul 20 23:27:37 CDT 2015hello0 receive
2 monjul 20 23:27:42 CDT 2015hello0 savelocal
3 Mon Jul 20 23:28:37 CDT 2015hello1 receive
4 Mon Jul 20 23:28:42 CDT 2015hello1 savelocal
5 monjul 20 23:29:37 CDT 2015hello2 receive
6 Mon Jul 20 23:29:42 CDT 2015hello2 savelocal
7 Mon Jul 20 23:30:37 CDT 2015hello3 receive
8 monjul 20 23:30:42 CDT 2015hello3 savelocal
9 Mon Jul 20 23:31:37 CDT 2015hello4 receive
10 monjul 20 23:31:42 CDT 2015hello4 savelocal
11 Mon Jul 20 23:32:37 CDT 2015hello5 receive
12 Mon Jul 20 23:32:42 CDN 2015hello5 savelocal
13 Mon Jul 20 23:33:37 CDT 2015hello6 receive
14 monjul 20 23:33:42 CDT 2015hello6 savelocal
15 monjul 20 23:34:37 CDT 2015hello7 receive

We can see that the save code is run after 5s of delay.

OK. Conclusion:
1. When the system is sleeping, the socket can receive packets on time.
2. After receiving the package, the program will immediately sleep again. To execute code for a long time in the future, it is best to obtain the wakelock to ensure that the code can be executed, and then release the wakelock. This is actually like BroadcastReceiver. During the onReceive function execution, the system will automatically help us get the wakelock. If this function is used, wakelock will be released. Therefore, if you want to execute code for a long time, then we need to get and release the wakelock ourselves, or the Framework provides a feature called WakefulBroadcastReceiver to do these things for us.

Note:When I only tested wifi, the BP just seems to mean that radio and wifi chips are not one thing, but it seems like 3G ~~~ Try again in another day

 

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.