How to download a image from URL in App
I'd like to know how I can download an Image from a given URL and display it inside an ImageView. And is there any permissions
required to ment开发者_开发知识库ion in the manifest.xml
file?
You need to put this permission
to access the Internet
<uses-permission android:name="android.permission.INTERNET" />
you can try this code.
String imageurl = "YOUR URL";
InputStream in = null;
try
{
Log.i("URL", imageurl);
URL url = new URL(imageurl);
URLConnection urlConn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.connect();
in = httpConn.getInputStream();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Bitmap bmpimg = BitmapFactory.decodeStream(in);
ImageView iv = "YOUR IMAGE VIEW";
iv.setImageBitmap(bmpimg);
Use background thread to get image and after getting image set it in imageview using hanndler.
new Thread(){
public void run() {
try {
Bitmap bitmap = BitmapFactory.decodeStream(new URL("http://imageurl").openStream());
Message msg = new Message();
msg.obj = bitmap;
imageHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
Handler code where we set downloaded image in imgaeview.
Handler imageHandler = new Handler(){
public void handleMessage(Message msg) {
if(msg.obj!=null && msg.obj instanceof Bitmap){
imageview.setBackgroundDrawable(new BitmapDrawable((Bitmap)msg.obj));
}
};
};
And ofcourse you need internet permission.
<uses-permission android:name="android.permission.INTERNET" />
You need to set usage
permission of INTERNET
in android manifest file and use java.net.URL
and java.net.URLConnection
classes to request the URL.
There is the BitmapFactory
-class which can do that. It can create a Bitmap
-object from an InputStream
, which can then be displayed in an ImageView
.
Something you should know is, that using a normal URLConnection
to get an InputStream
on a URL
-object does not always work with the bitmap-factory. A work-around is presented here: Android: Bug with ThreadSafeClientConnManager downloading images
look this:
Option A:
public static Bitmap getBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
bis.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return bm;
}
Option B:
public 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);
input.close();
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Jus run the method in a background thread.
精彩评论