记得之前做安卓应用时都是在2.2以下的版本,如果在UI线程中进行耗时操作,比如http,socket等 会产生android.os.NetworkOnMainThreadException 如果异步加载网络图片,要在非UI线程中进行,请问有什么实现的例子吗

推荐图书

  • Android 2高级编程(第2版)
  • Google Android SDK开发范例大全(第2版)
  • 疯狂Android讲义


1个回答

package com.allen.utils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class Utils {    
    /**
     * 获取网络中图片资源
     * @param src 图片地址
     * @return drawable对象
     */
    public static Drawable loadImage(String src){
        URL url=null;
        try {
            url = new URL(src);
        } catch (MalformedURLException e) {
            Log.e("-Utils-->MalformedURLExcetion--", e.toString());
        }
        InputStream is=null;
        try {
            is = url.openStream();
        } catch (IOException e) {
            Log.e("-Utils-->IOException--", e.toString());
        }
        Drawable drawable=Drawable.createFromStream(is, "img");
        return drawable;
    }
    /**  
     * 从网络上下载  
     * @param url  
     * @return  
     */  
    public static Bitmap getBitMapFromUrl(String url) {   
        Bitmap bitmap = null;   
        URL u =null;   
        HttpURLConnection conn = null;   
        InputStream is = null;   
        try {   
            u = new URL(url);   
            conn = (HttpURLConnection)u.openConnection();   
            is = conn.getInputStream();   
            bitmap = BitmapFactory.decodeStream(is);   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
        return bitmap;   
    }   

    /**  
     * 从缓存中读取  
     * @param url  
     * @return  
     * @throws Exception   
     */  
    public static Bitmap getImgFromCache(String url,Map<String,SoftReference<Bitmap>> imgCache) throws Exception {   
        Bitmap bitmap = null;   
        //从内存中读取   
        if(imgCache.containsKey(url)) {   
            synchronized (imgCache) {   
                SoftReference<Bitmap> bitmapReference = imgCache.get(url);   
                if(null != bitmapReference) {   
                    bitmap = bitmapReference.get();                                  
                }   
            }   
        } else {//從網絡中下載  
            bitmap = getBitMapFromUrl(url);   
            //将图片保存进内存中   
            imgCache.put(url, new SoftReference<Bitmap>(bitmap));             
        }   
        return bitmap;   
    }   

}