I created a multi-threaded application, but it still freezes if the server is unavailable.
In the main event, I created the following methods:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
...
establishTCPConnection();
...
}
private void establishTCPConnection(){
TCPClientServiceThread = new Thread(null, backgroundConnection, "connection");
TCPClientServiceThread.start();
}
..
private Runnable backgroundConnection = new Runnable(){
public void run(){
doEstablishTCPConnection();
}
};
private void doEstablishTCPConnection()
{
startService(new Intent(this, TCPClientService.class));
}
And this is the TCPClientService class:
public class TCPClientService extends Service{
...
private String serverAddress = "192.168.1.5";
private int portNumber = 1000;
@Override
public void onCreate()
{
connectionAvailable = false;
IntentFilter dataReceiverFilter;
dataReceiverFilter = new IntentFilter(MotranetClient.MOTION_DATA_UPDATED);
dataReceiver = new DataReceiver();
registerReceiver(dataReceiver, dataReceiverFilter);
EstablishConnection();
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
private void EstablishConnection()
{
try {
InetAddress serverAddr = InetAddress.getByName(serverAddress);
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, portNumber);
String message = "testing connection";
try {
Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(message);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
connectionAvailable = true;
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
connectionAvailable = false;
} finally {
socket.close();
announceNetworkAvailability(connectionAvailable);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
announceNetworkAvailability(connectionAvailable);
}
}
}
If the server is unavailable, line
Socket socket = new Socket(serverAddr, portNumber);
causes some delay, and I think this is a reason for freezing. But if the TCPClientService service is running in its own thread, I do not know why this affects the timeout of the main action.
I would be very grateful if anyone could show how to prevent the application from freezing when the server is unavailable.