Android image fetching

后端 未结 2 478
北海茫月
北海茫月 2020-12-17 06:29

What is the simplest way to fetch an image from a url in an android program?

2条回答
  •  情书的邮戳
    2020-12-17 06:34

    You do it many ways but the simplist way I can think of would be something like this:

    Bitmap IMG;
    Thread t = new Thread(){
        public void run(){
        try {
            /* Open a new URL and get the InputStream to load data from it. */ 
            URL aURL = new URL("YOUR URL"); 
        URLConnection conn = aURL.openConnection(); 
        conn.connect(); 
        InputStream is = conn.getInputStream(); 
        /* Buffered is always good for a performance plus. */ 
        BufferedInputStream bis = new BufferedInputStream(is); 
        /* Decode url-data to a bitmap. */ 
        IMG = BitmapFactory.decodeStream(bis);
        bis.close(); 
        is.close(); 
    
        // ...send message to handler to populate view.
        mHandler.sendEmptyMessage(0);
    
    } catch (Exception e) {
        Log.e(DEB, "Remtoe Image Exception", e);
    
        mHandler.sendEmptyMessage(1);
    } finally {
    }
    }
    };
    
    t.start();
    

    And then add a handler to your code:

        private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            switch(msg.what){
            case 0:
                (YOUR IMAGE VIEW).setImageBitmap(IMG);
                break;
            case 1:
                onFail();
                break;
            }
        }
    };
    

    By starting a thread and adding a handler you are able to load the images without locking up the UI during download.

提交回复
热议问题