In my Android app I have written a service that connects to a server. I am calling Java socket .getOutputStream().write
and .getInputStream().read
to write requests and read responses to and from the server. It is plain and simple as that.
Everything works fine until device sleeps.
When device sleeps, server disconnects app connection. Eventually when device wakes up, my app service starts running. But it never detects disconnected connection. .getInputStream().read
keeps waiting for responses forever and .getOutputStream().write
also writes requests to socket successfuly. This is really weird.
Thus for Java, socket is normal even though it is disconnected by server. And there is no way to detect the same.
Ideally, .getInputStream().read
should return -1 immediately after device wakes up and service starts running. But it doesn't happen. Neither .getOutputStream().write
throws IOException
. And user has only way to stop application forcefully through app settings, which is not at all acceptable from app perspective.
What I tried?
I have gone through relevant question like this, this and this but the answers there suggests to write or read from socket to check if its still connected (like heartbeats as suggested here). However, as I stated this doesn't work in my case (i.e. Socket read keeps waiting and write doesn't throw any exception, as if socket is still connected)
As a workaround I thought of closing and reconnecting connection compulsory (regardless it is already connected or not) after device wakes up. But I couldn't find specific intent for device wake up. (Some posts on SO suggested
android.intent.action.SCREEN_ON
for device wake up. But I definitely don't want to reset connection every time when just screen turned on. No, it has to be really device wakeup intent.)
I am badly stuck and like to know how they handle this situation in many other apps which stay connected to their servers.