onPostExecute 不是 运行

onPostExecute not running

我有一个单独的 class(不是 Activity)来管理图像及其属性。

在这个 class (Image.class) 中,我还创建了一个 AsynkTask 来从 Web 下载位图。 一切正常,除了 AsyncTask 保持 运行,而没有触发 onPostExecute() 方法。

有人可以帮帮我吗?

我在 Main Activity 循环中实例化了这个 class。

public class InstaImage {

public URL thumbUrl;
public URL lowresUrl;
public URL standardresUrl;

private URL url;
private Bitmap bmp;

public InstaImage(URL _thumb, URL _low, URL _standard ) {
    this.thumbUrl = _thumb;
    this.lowresUrl = _low;
    this.standardresUrl = _standard;
}

public Bitmap getBitmap(String resolution) {

    switch(resolution) {
        case "thumb":
            url = thumbUrl;
            break;

        case "low":
            url = lowresUrl;
            break;

        case "standard":
            url = standardresUrl;
            break;
    }

    DownloadImageTask dit = new DownloadImageTask();

    dit.execute();

    // --- TEST ASYNC STATUS ---
    while(dit != null) {

        if(dit.getStatus() == AsyncTask.Status.FINISHED) {
            Log.i("ASYNC", "END2!!");
            break;
        }
        else {
            Log.w("ASYNC WAITING", dit.getStatus().toString());
        }
    }

    // --- END TEST ASYNC STATUS ---

    return bmp;
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    URLConnection conn = null;
    InputStream in = null;
    Bitmap _bmp = null;

    @Override
    protected Bitmap doInBackground(String... urls) {
        Log.i("ASYNC","STARTING!!");
        try {
            conn = url.openConnection();

            if (conn != null) {

                in = conn.getInputStream();

                _bmp = BitmapFactory.decodeStream(in);

                in.close();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        Log.i("ASYNC","END0!!");

        return _bmp;
    }


    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        Log.i("ASYNC","END1!!");
        bmp = result;
    }
}
}

你对线程的工作原理有误解。您正在使用异步调用,然后正忙于等待它完成。

// --- TEST ASYNC STATUS ---
while(dit != null) {

    if(dit.getStatus() == AsyncTask.Status.FINISHED) {
        Log.i("ASYNC", "END2!!");
        break;
    }
    else {
        Log.w("ASYNC WAITING", dit.getStatus().toString());
    }
}

// --- END TEST ASYNC STATUS ---

return bmp;

抱歉,您可能需要阅读相关主题。

我建议制作一个 class InstaImageView extends ImageView 并在其中添加一个异步 URI 加载程序。我敢肯定这段代码已经被写了一千遍了。不懂线程,不懂异步编程的可以照搬。

你为什么 return 从 doInBackground 函数中调用?

return_bmp; // 这里不需要return //结果会自动传给onPostExcute()