I am developing an application in Android that connects to a server using TCP Sockets. I am using AsynkTask to connect with the application.
The Application does not disconnect from the server in his entire life cycle. Even if the application goes to sleep the AsynkTask keeps running and the socket is always connected.
The Socket is disconnected only when the server closes the socket (because an exception is throwed and the doInBackground() finish )or when the user exit the application (because the AsyncTask is cancelled)
This is my doInBackground()
@Override
public Void doInBackground(Void ...pa){
try {
sock = new Socket(InetAddress.getByName(serv), port);
}
catch(IOException ex) { errMessage = ex.getMessage() + "\n"; }
try {
if(sock != null) {
inStr = new DataInputStream(sock.getInputStream());
outStr = new DataOutputStream(sock.getOutputStream());
while(!isCancelled()) {
if(((hbDataSize = inStr.read()) & 0xC0) == 0xC0){
lbDataSize = inStr.read();
packetSize = (hbDataSize << 8 & 0x3F00) + lbDataSize;
buffer = new byte[packetSize-2];
inStr.read(buffer, 0, packetSize-2);
publishProgress(0);
}
}
} else {
throw new IOException(errMessage);
}
}catch(IOException e) { // sin conexion salta a a excepcion
errMessage = e.getMessage();
publishProgress(2);
isError = true;
}
return null;
}
Anyway i just put the code so you can see the method.
I start reading about AsyncTask and it says that i should use an AsyncTask for long periods of time.
AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.
My app works fine, but should i change the AsyncTask for a Executor, or a ThreadPoolExecutor or a FutureTask ? And if you think i should change it, why should i change it? I've been reading about those three clases, but i am not shure if i should change it.