Issue
I'm working on some "sockets-application" and i need help. I have a class with connection-method:
public class ClientSocketConnection {
private int port = 49150;
private String host;
public ClientSocketConnection(String host){
this.host = host;
}
public boolean connect(){
Boolean isConnected = false;
AsyncTask<Void, Void, Boolean> asyncProcess = new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... voids) {
try {
Socket client = new Socket();
client.connect(new InetSocketAddress(host, port), 1000);
} catch (IOException ex) {
Log.d(TAG, "Client socket exception", ex);
return false;
}
return true;
}
};
asyncProcess.execute();
try {
isConnected = asyncProcess.get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return isConnected;
}
I'm trying to establish a socket-connection using AsyncTask in Application-class:
private void executeRequest(){
ClientSocketConnection client = new ClientSocketConnection(txtIPAddress.getText().toString());
AsyncTask<Void, Void, Boolean> connectionTask = new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... voids) {
Log.d(TAG, "Begin");
boolean flag = client.connect();
Log.d(TAG, "End");//Not displayed
return flag;
}
@Override
protected void onPostExecute(Boolean isConnected) {
if(isConnected){
Toast.makeText(getApplicationContext(), "Connection established", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Incorrect IP-Address", Toast.LENGTH_SHORT).show();
}
}
};
connectionTask.execute();
}
But doInBackground-method in executeRequest() does not work completely (End-message isn't displayed). But, interestingly, everything is fine without using AsyncTask in Application class, when doing it in main (UI) thread...
What could be the problem? There are no errors in the log. The application continues to work...
Thanks in advance))
Solution
Because you're calling AsyncTask.get(). That's causing you to not be asynchronous and block until the task is finished. That function should never be called. There's very limited uses for it, and if you're not trying to do something very unusual its wrong. There's also no reason to have 2 async tasks here.
Which is your second problem- 2 async tasks. AsyncTasks all share the same thread, and are executed round robin. That means task 2 can't be exeucted until task 1 finishes- but you have task 1 waiting for task 2, which will never start. You basically deadlocked yourself.
Solution: do not use AsyncTask.get(). Rewrite this to use a single AsyncTask, or to use real Threads (this is generally preferable for networking, as if you use AsyncTasks elsewhere in the app they will all be blocked waiting for the network request to finish).
Answered By - Gabe Sechan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.