I am trying to connect to a host in my local network. Reaching it works from my computer or my android phone (SGS2) and it seems it also works from withing my app, but I want to get a result to check if it worked and depending on that proceed with further actions.
I am using an implementation of ASyncTask, named Connector.
When I call Connector I don’t just call execute but also get() in order to receive a boolean value denoting the success. The problem here is that execute performs fine (the host is definitely reached and I land at my breakpoints in doInBackground.
But how can I receive the boolean value which I return in doInBackground?
When I call get() it never finishes…
Basically, what I care about is the variable “connected”, but get() seems to run perpetuously!
Permissions are granted in the manifest, wifi on my phone is enabled and works, I can reach the host.
This is where I execute Connector:
url = new URL("http://192.168.2.103/?LED=T");
Connector connector = new Connector();
AsyncTask<URL, Integer, Boolean> execute = connector
.execute(url);
Status status = execute.getStatus();
boolean connected = false;
try {
Log.d("MainActivity", "trying to get result");
connected = connector.get();
Log.d("MainActivity", "got result");
} catch (InterruptedException ie) {
ie.printStackTrace();
} catch (ExecutionException ee) {
ee.printStackTrace();
}
System.out.println();
} catch (MalformedURLException e) {
e.printStackTrace();
}
//do something depending on connected
And this is Connector:
public class Connector extends AsyncTask<URL, Integer, Boolean> {
public static boolean connect(URL url) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url.toString());
System.out.println();
try {
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
Log.d("myapp", "response " + response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
protected Boolean doInBackground(URL... params) {
boolean connect = connect(params[0]);
return connect;
}
@Override
protected void onPostExecute(Boolean result) {
Log.d("Connector", "onPostExecute");
super.onPostExecute(result);
}
}
I don’t think you want to call
get()since you have already run the AsyncTask withexecute(). If you just want to see that the connected variable is being set then use aLofin youronPostExecute()since the result fromdoInBackgroundis sent to it. If you need to do something with it then you can do that inonPostExecute()as well