仅在异步任务完成后执行代码

时间:2012-10-31 16:36:50

标签: android android-asynctask

我有以下三行代码。

Line 1 : GetBitMapFromURL gbmap = new GetBitMapFromURL();   //Obtain thumbnail bitmap
Line 2 : gbmap.execute(applicationThumbNailURL);
Line 3 : applicationThumbnailBitMap = gbmap.returnBitmap();

我希望只有在执行了GetBitMapFromURL异步任务的onPostExecute之后才能执行第3行。

1 个答案:

答案 0 :(得分:3)

在GetBitMapFromURL中创建一个回调。

public class GetBitMapFromURL extends AsyncTask<Void, Void, Void> {

    private GetBitMapFromURLCallback mCallback = null;

    public WebService(GetBitMapFromURLCallback callback) {
        mCallback = callback;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // ...
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        if (mCallback != null) {
            mCallback.onGetBitMapFromURLComplete(this);
        }
    }

    public interface GetBitMapFromURLCallback {

        public void onGetBitMapFromURLComplete(GetBitMapFromURL getBitMapFromUrl);
    }
}

public class MyActivity extends Activity implements GetBitMapFromURLCallback {

    // ...

    public void onGetBitMapFromURLComplete(GetBitMapFromURL getBitMapFromUrl) {
        // This code will get called the moment the AsyncTask finishes
    }
}

让您的活动实现此回调和onGetBitMapFromURLComplete()