I have an AsyncTask
which I am using to create a Socket
connection. Within my doInBackground()
method, I have:
Socket socket = new Socket(HOST_NAME, PORT_NUMBER);
For my case, this line of code hangs when I try to connect via a cellular network. It never finishes executing and eventually the app crashes. Because the information from the Server
was necessary to me, I did something like this:
AttemptConnection attemptConnection = new AttemptConnection(); // this is the AsyncTask
attemptConnection.execute().get();
Now I realize this is bad because the purpose of AsyncTask
is to run parallel to the main thread and this is halting processing on the main thread. However, my app can't really go anywhere until the information from the Server is acquired so I kind of NEED this AsyncTask to finish.
Because the Socket
connection fails and hangs some times though, there are cases where this causes freezes on my device and an eventual crash of my app. So I want something better. The solution I came up with is:
attemptConnection.execute();
try {
Thread.sleep(3000);
} catch (Exception e) {
}
attemptConnection.cancel();
But I wonder if this is any better? I can't cancel the process internally because the try / catch
that should catch errors with the Socket
connection is never reached. The code hangs there and no errors are ever caught. But the above idea also seems like a really hacky way to do it; I'm wondering if this approach is as bad as my gut tells me it is, and if so, what are some better ways to handle this?