Android AsyncTask无法下载图片

时间:2013-04-11 14:38:31

标签: android asynchronous

我希望有人可以帮助我解决我一直遇到的问题。我正在使我的应用程序在大于3.0的版本上工作,所以我只能在UI线程上执行GUI任务。我有以下代码,我没有编译错误,但它无法正常工作。在日志中我收到以下错误:

I / AndroidRuntime(464):注意:附加线程'Binder Thread#3'失败

感谢您的帮助!

new DownloadImageTask().execute(imgURL); //imgURL is declared as string URL

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

     protected void onPostExecute(Bitmap result) {
        ((ImageView) findViewById(R.id.imgCity)).setImageBitmap(bmp);
     }

    protected Bitmap doInBackground(String... params) {
        return loadImage(params[0]);
    }

}


public Bitmap loadImage(String poiURLimg) {

    try {
        URL ulrn = new URL(poiURLimg);
        HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();
        InputStream is = con.getInputStream();
        bmp = BitmapFactory.decodeStream(is);
        if (null != bmp)
        return bmp;
    } catch (Exception e) {
    }
    return bmp;
}

2 个答案:

答案 0 :(得分:1)

Binder Thread#3错误与您应用中的代码无关。有很多潜在的原因通常与日食有关。您可以阅读this post,其中提供了一些示例。

至于为什么Bitmap不会加载 - 在onPostExecute中,您要将ImageView的位图设置为bmp。 Bmp是创建位图的loadImage方法返回的值的名称。它不是作为参数传递到onPosExecute的Bitmap的名称 - 即Bitmap结果。将bmp更改为结果,它应该工作。

答案 1 :(得分:0)

要尝试的几件事。首先,确保您已将INTERNET权限添加到AndroidManifest.xml文件中。你需要从互联网上下载图像,你的应用程序会在没有它的情况下崩溃(尽管听起来这不是你的问题)

尝试将此用于loadImage()方法:

public static Bitmap loadImage(String src)
    {
        try
        {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }

以下是我目前在我的应用中编写并使用的DownloadImageTask示例(所以我知道它可以正常工作):

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
    @Override
    protected Bitmap doInBackground(String... params)
    {
        return loadImage(params[0]);
    }

    @Override
    protected void onPostExecute(Bitmap result)
    {
        if (isCancelled() || result == null)
            return;

        ((ImageView) findViewById(R.id.image_view)).setImageBitmap(result);
    }
}