Socket coding in Android

So I’ve recently been playing about with Android for ‘Not So Super Secret Startup Idea’ and needed some code to communicate data such as Phone Calls/Text messages and other things from my phone to another device using TCP/IP. This is a bit harder on Android then it is on a PC as Android is bassed on apps having something called Activities and Services.
An Activity is the part of the Application which handles user input and can be destroyed at any time by the OS. This makes it pretty much useless for running anything which will communicate with the outside world without user intervention.
The other part part of an Android app is called a service which can be used to perform tasks in the background, process events from Activities, etc.
So what I currently have is an Android app which has a Service to handle TCP/IP communications from a telnet client on a PC. The service will also send data such as GPS location, phone calls and text messages (currently work in progress) over the socket to the PC.
One problem with the default TCP/IP functions is that they block (do not return until the right amount of data is received). I choose to use threads to handle blocking I/O and post Intents (a form of IPC) to the main activity to update it’s UI.
There is however one problem with using Threads in that when the Service is stopped there is no clean way to Kill a thread. This can be gotten around by closing the socket and setting a variable inside the threads main loop to tell it that it needs to shutdown cleanly.
So here’s some quick and dirty code which output’s GPS location and the phone no. of any calls received to a socket:

GPSTest

One thought on “Socket coding in Android”

  1. You’d best be careful not to connect the interface port to a power socket like they did to poor R2 D2. And don’t forget that it’s probably not the droid you’re looking for.

Comments are closed.