gpt4 book ai didi

android - 从网络中拉取图像

转载 作者:行者123 更新时间:2023-11-30 04:50:04 27 4
gpt4 key购买 nike

我正在使用以下代码从网络上抓取图像。它使用 Gridview 并根据位置从数组中选择一个 URL。它可以工作,但图像的加载经常会受到打击或错过。几乎每次我启动该应用程序时,都会加载不同数量的图像。

从纵向 View 更改为横向 View 时也有问题,10 张图像中可能会显示 5 张,然后我会转动设备,通常会丢失所有图像。不过,有时确实会出现一些。

有什么想法可以使它更健壮吗?

try {
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
return bm;
} catch (IOException e) {
Log.d("DEBUGTAG", "error...");
}
return null;

最佳答案

我读到的一件事是,从 InputStream 解码位图存在一个已知错误,Google 建议的修复方法是使用 FlushedInputStream(以下 URL 中的示例):

http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html

此外,我会将下载代码放入 AsyncTask 中。这是我目前使用的:

public static Bitmap loadImageFromUri(URI uri)
{
URL url;
try {
url = uri.toURL();
} catch (MalformedURLException e) {
Log.v("URL Exception", "MalformedURLException");
return null;
}

try
{
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(new FlushedInputStream(input));
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}

由于我设置其余代码的方式,我只传递了一个 URI,您可以传递一个 URL 并跳过第一部分。这将使下载不会占用您的 UI 线程。

关于android - 从网络中拉取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3774189/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com