Android - How to download an image and use it as new resource?
I want to download image from distant server and use it as resource. Is 开发者_开发技巧it possible ? How can I do this ?
Is it possible ?
You can download an image. It will not be a "resource", though. Resources are packaged inside the APK and cannot be modified or added to at runtime.
That's how I did it:
private class ImgDownload extends AsyncTask {
private String requestUrl;
private ImageView view;
private Bitmap pic;
private ImgDownload(String requestUrl, ImageView view) {
this.requestUrl = requestUrl;
this.view = view;
}
@Override
protected Object doInBackground(Object... objects) {
try {
URL url = new URL(requestUrl);
URLConnection conn = url.openConnection();
pic = BitmapFactory.decodeStream(conn.getInputStream());
} catch (Exception ex) {
}
return null;
}
@Override
protected void onPostExecute(Object o) {
view.setImageBitmap(pic);
}
}
Yes you cannot download it as a resource file..you can download and store images on your SDCard or database and load it from there...
To check how to download images to SDCard refer to this link
http://snippets.dzone.com/posts/show/8685#related
You can later load it from your SDCard like this
http://android-er.blogspot.com/2010/01/how-to-display-jpg-in-sdcard-on.html
This is how you store and retrieve images from ur DB
http://www.helloandroid.com/tutorials/store-imagesfiles-database
This problem was discussed and solved by Gilles Debunne, an engineer in the Android Group, in the blog post Multithreading For Performance.
It uses already an AsyncTask
internally. Since it is made for Android it is able to download an image and set it directly to an ImageView
with the following two lines of code:
ImageDownloader imageDownloader = new ImageDownloader();
imageDownloader.download(url, imageView);
The ImageDownloader
class can be found in the linked repository.
精彩评论