Android What happens during HTTP transaction if Device sleeps?

387 Views Asked by At

I couldn't produce this example which iam about to explain, so i post this here to give me more info about it.

Lets say that we want to make an http request to receive a JSON object from a server. We hold no wakelocks nor we make our app a foreground. We make the connections and we wait for our response from server.

What if the device goes to sleep at that very moment (waiting for the JSON object). Do we get the object when the device awakes or we get a timeout exception?

NOTE

Do not involve doze mode in this example. Just that device goes to sleep. Thank you

2

There are 2 best solutions below

3
Karan Harsh Wardhan On BEST ANSWER

When an Android is kept idle, the device locks and then it goes to deep sleep mode. In deep sleep mode the Android system, closes the existing network connections like TCP or UDP. If your app is connected to a server, it loses connection to the server and tries to reconnect based on the reconnect attempt methods configured for the client. But if your app is the server, all the client will lose connection to the server, and you have to start the socket again in server and try to connect once again from the clients.

From https://stackoverflow.com/a/33366487/806328

retrofit just "listens" for network connection, when it loses it - connection time out error after specified time

1
Abdul Waheed On

In this case, your device will got to sleep and you will get Activity Life Cycle Method Call back that is onPause() and onStop while your service will be running. This process will not make your webservice call stop. Once you get response from server your app will get call back (if you have implemented). And nothing bad will happen until you have killed your app before going to sleep. If after web service you may be accessing some variables belonging to activity that started web service. This will lead crashing.call. When you undo sleeping state you will get call back of onStart and onResume That means when your device went to sleep it did not kill your activity.