[英]Load image from URL - Java
I am trying to load an image from a url in the handelResponse
of my ASYNC Task that makes a GET request, and in handelResponse
I have this 我正在尝试从发出GET请求的ASYNC任务的
handelResponse
中的URL加载图像,并且在handelResponse
我有这个
InputStream is = (InputStream) new URL(homeScreenPicUrl).getContent();
b = BitmapFactory.decodeStream(is);
But my ASYNC Task seems to have a problem with this as I get W/System.err﹕ android.os.NetworkOnMainThreadException
how could I load the image in the hadelResponse
, ideally I want to load it syncronously as I want to wait for it to load before moving to the next screen. 但是我的ASYNC任务似乎与此有问题,因为我得到
W/System.err﹕ android.os.NetworkOnMainThreadException
我该如何将图像加载到hadelResponse
,理想情况下我想同步加载它,因为我想等待它请先加载,然后再转到下一个屏幕。
And since this is all happening on the splash screen I am just waiting for the pic before moving to the main page. 而且由于这都是在初始屏幕上发生的,所以我只是在等待图片,然后再转到主页。
Thanks 谢谢
This is because InputStream
is just a handler: when you read()
from it (which is what BitmapFactory
does) you are in fact fetching data from the network, and Android forbids it because you are slowing the system. 这是因为
InputStream
只是一个处理程序:当您从中read()
( BitmapFactory
所做的事情)时,实际上是从网络中获取数据,而Android则禁止这样做,因为这会降低系统速度。
Either you decode the stream in the background thread and change the return type of the AsyncTask
to Bitmap
, or you store the content of the stream in a byte[]
and use that byte[]
to build the image in the UI thread. 您要么在后台线程中解码流,然后将
AsyncTask
的返回类型更改为Bitmap
,要么将流的内容存储在byte[]
然后使用该byte[]
在UI线程中构建图像。 Both solution are equivalent because you are consuming the stream in the background thread and store its content in memory. 这两种解决方案是等效的,因为您正在后台线程中使用流并将其内容存储在内存中。
public byte[] consume(InputStream in) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int read = -1;
while ((read = in.read(buffer)) > 0) {
out.write(buffer, 0, read);
}
return out.toByteArray();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.