我使用回调。
MyCallback.java
public interface MyCallback<T> {
public void onComplete(T result);
}
MyAsyncTask.java
public class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
private MyCallback<Boolean> mCallback;
public MyAsyncTask(MyCallback<Boolean> callback) {
mCallback = callback;
}
@Override
protected void onProgressUpdate(Void... progress) {
super.onProgressUpdate(progress);
// ...
}
@Override
protected Boolean doInBackground(Void... params) {
// ...
}
@Override
protected void onPostExecute(Boolean result) {
if (mCallback != null) {
mCallback.onComplete(result); // will call onComplete() on MyActivity once the job is done
}
}
}
在此示例中,此回调将不接受任何参数并返回一个Boolean
.
现在您所要做的就是让您的调用类(MyActivity
例如)实现MyCallback
:
public class MyActivity extends Activity implements MyCallback<Boolean> {
// ...
xxx {
MyAsyncTask myAsyncTask = new MyAsyncTask(this); // the callback
myAsyncTask.execute();
}
// ...
@Override
protected void onComplete(Boolean result) {
// ...
}
}
这就是我所做的,而且效果很好。