当前位置:操作系统 > 安卓/Android >>

android异步回调加载网络图片

 

在做应用的时候很多时候都会去从网络加载图片,而且还要做各种各样的加载效果。比如,加载图片的时候在图片上显示loading的图片,图片加载完成时loading消失,加载失败又有相应的处理。如果处理不好就会很麻烦,下面总结了一个轻量级的从网络加载图片方法。

 

 

package com.jacp.util; 

 

import java.io.File; 

import java.io.IOException; 

import java.net.HttpURLConnection; 

import java.net.MalformedURLException; 

import java.net.URL; 

 

import android.graphics.Bitmap; 

import android.graphics.BitmapFactory; 

import android.os.Handler; 

import android.os.Message; 

 

public class Utils 

 

    /**

     * 加载图片

     * @param url 图片的url

     * @param listener 回调易做图

     */ 

    public void loadImage(final String url, final OnLoadImageListener listener) 

    { 

        if (null == url || null == listener) 

        { 

            return; 

        } 

         

        final Handler handler = new Handler() 

        { 

            public void handleMessage(Message msg) 

            { 

                listener.onLoadImage((Bitmap) msg.obj, url); 

            } 

        }; 

         

        // 之前根据url写入本地缓存的路径 

        String path = ""; 

        File file = new File(path); 

        if (file.exists()) 

        { 

            Bitmap bm = BitmapFactory.decodeFile(path); 

            sendMessage(handler, bm); 

            return; 

        } 

 

        new Thread(new Runnable() 

        { 

            public void run() 

            { 

                try 

                { 

                    // 网络加载图片,还可以加入延迟(time out)条件 

                    URL u = new URL(url); 

                    HttpURLConnection httpConnection = (HttpURLConnection) u.openConnection(); 

                    if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) 

                    { 

                        Bitmap bm = BitmapFactory.decodeStream(httpConnection.getInputStream()); 

                        sendMessage(handler, bm); 

                        // 同时对图片进行缓存... 

                        return; 

                    } 

                     

                    // 没有请求到图片 

                    sendMessage(handler, null); 

                } catch (MalformedURLException e) 

                { 

                    sendMessage(handler, null); 

                } catch (IOException e) 

                { 

                    sendMessage(handler, null); 

                } 

            } 

        }).start(); 

             

    } 

     

    /**

     * 向handler发送处理的消息

     * @param handler

     * @param bm

     */ 

    private void sendMessage(Handler handler, Bitmap bm) 

    { 

        Message msg = handler.obtainMessage(); 

        msg.obj = bm; 

        handler.sendMessage(msg); 

    } 

     

    /**

     * 加载图片时的回调

     *

     */ 

    public inte易做图ce OnLoadImageListener&n

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,