A clean way to use AsyncTask to get a result would be to use a callback interface.
Here is a simple example of this concept:
interface AsyncTaskCompleteListener<T> {
public void onTaskComplete(T result);
}
then in your B class :
class B implements AsyncTaskCompleteListener<String> {
public void onTaskComplete(String result) {
// do whatever you need
}
public void launchTask(String url) {
A a = new A(context, this);
a.execute(url);
}
}
you should now add the following code to your A class:
class A extends AsyncTask<String, Void, String> {
private AsyncTaskCompleteListener<String> callback;
public A(Context context, AsyncTaskCompleteListener<String> cb) {
this.context = context;
this.callback = cb;
}
protected void onPostExecute(String result) {
finalResult = result;
progressDialog.dismiss();
System.out.println("on Post execute called");
callback.onTaskComplete(result);
}
}
This way, you don't need to wait explicitely for your task to complete, instead, your main code (which is probably the main UI thread), is waiting in the normal android event loop, and the onTaskComplete method will be automatically called, allowing to handle the task result there.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…