I have built an Android chat application. It has a TCP server which is connected to via using a Socket.
I want the server connection to work in the background always – even if the app is not in foreground – and listen to data sent from the server.
For now I am using a while loop to checking if there is something new, but the OS close my thread when Android needs resources.
I have thought about using the readline() method in my thread instead of using the while loop because readline() is a blocking method.
Is this the right approach to take, which will lead to, prevention of the OS from killing my application?
Is there any way, like a custom broadcast receiver that will launch only when the incoming socket is available?
Thanks!
In short, Android can and will kill any applications that hog up resources in order to keep running. The onus is on you on how to handle the scenarios which can threaten your app to be killed.
I suggest looking at the service’s life-cycle as found on the developer‘s site.
For a start, any application, be it service/activity, that hogs up too much, in this manner is considered… “rude” in the eyes of Android, and therefore, is prepared to be killed in this manner regardless!
For example, listen in the
onLowMemoryoverride method and act accordingly, such as saving data and what-nots.What really, should be happening, is this, the service, spawns a thread to periodically listen for incoming connections in this manner,
The
terminatingvariable is abooleanand is the deciding variable that controls when to terminate the loop. Notice how theThread.sleepmethod is used, to “calm down” the execution, if omitted, Android will put a cross-hair on the app and terminate it, in other words, be polite to system resources.Hint: Extend the
Threadclass, to hold the functionality of handling incoming connections via theaccept()method.When the
incomingClientSocketbecomes non-null, then another thread is created in which it opens the input/output stream of theincomingClientSocketand read/write to it using binary fashion.Do not use the
readlinemethod as that is an indication of poor design and assuming the data is text-ual, because one incoming packet to the client could be for example, 720bytes, the next packet coming in after that, could well be 564 bytes, that is the nature of TCP/IP.You need to come up with a more reliable way of establishing boundaries for the data transmission, for example, a begin and end marker, and let the server read the incoming data and distinguish the byte stream that composes of a begin and end markers, once both are present, then extract the real data in-between the markers and act on it accordingly.
You could for instance, say, upon
incomingClientSocketthat actually becomes non-null, send a broadcast to your activity to act on it, and let the activity, take that socket, and open the connection and read/write to/from the input/output streams associated with the socket.