我一直在尝试将图片下载到位图元素中,将它们加载到带图像的gridView中,但我需要将其作为异步,因为如果没有,则会出现错误" android.os.NetworkOnMainThreadException&# 34 ;.
搜索我发现了很多教程,但是所有教程都在完成时将这个元素添加到ImageView中。 有没有办法做到这一点,但进入Bitmap?
在这里,我可以在没有发现异步的情况下下载:
URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
还有一个:
public static Bitmap getBitmapFromURL(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;
}
}
答案 0 :(得分:0)
将getBitmapFromURL
方法换入AsyncTask
,见下文:
private class GetBitmapFromURLAsync extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
return getBitmapFromURL(params[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
}
}
将上述AsyncTask
嵌入您的活动:
public class MyActivity extends Activity {
// To store the Bitmap returned by doInBackground asynctask
private Bitmap result;
// existing Activity code
...
private class GetBitmapFromURLAsync extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
return getBitmapFromURL(params[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
// return the bitmap by doInBackground and store in result
result = bitmap;
}
}
并致电以上代码:
GetBitmapFromURLAsync getBitmapFromURLAsync = new GetBitmapFromURLAsync();
getBitmapFromURLAsync.execute("http://....");
答案 1 :(得分:0)
你无法从android中的主(UI)线程进行重要的操作,如http请求。或者你会得到那个错误。您可以使用AsyncTask。
class ImageDownloadTask extends AsyncTask<String, Void, Bitmap> {
//this operation is in backgrouund
@Override
protected Bitmap doInBackground(String... params) {
return getBitmapFromURL(params[0]);
}
//operation is finished, update the UI with bitmap
@Override
protected void onPostExecute(Bitmap bitmap) {
}
}
或者只使用Picasso库,它确实适用于您,包括缓存。
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);