The point of using AsyncTasks
is to release the UI thread to other activities while some processing gets done on a non-UI thread in the AsyncTask
.
However, in your code the UI thread (which gets priority) is locked into the while()
loop waiting for a non-UI thread (which wont get priority) to complete the AsyncTask
.
A better approach would be a different flow. First, initiate the connection:
public void ensureConnected(Context parent, String url){
new CheckURL(parent, new OnTaskCompleted(){
@Override
public void onTaskCompleted(boolean result) {
isChecked = true;
isConnected = result;
// Change of state actions called from here
}}, url).execute();
}
And in the AsyncTask
:
private class CheckURL extends AsyncTask<Void, Void, Boolean>{
private Context parent;
private OnTaskCompleted listener;
private String url;
public CheckURL(Context parent, OnTaskCompleted listener, String url){
this.parent = parent;
this.listener = listener;
this.url = url;
}
@Override
protected Boolean doInBackground(Void... params){
// Do some stuff and return a boolean
}
@Override
protected void onPostExecute(Boolean result){
super.onPostExecute(result);
listener.onTaskCompleted(result);
}
}
Finally, I'm not sure why you need an Interface
here at all: you could do away with it entirely (as far as this simple example code goes) and set the state variables and trigger state change actions directly in onPostExecute
.