How to download a image from URL in App

后端 未结 5 510
长情又很酷
长情又很酷 2021-01-03 14:40

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 men

5条回答
  •  伪装坚强ぢ
    2021-01-03 15:21

    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.

    
    

提交回复
热议问题