×

Android异步从网络下载图片并且缓存图片到本地(二)

Kalet Kalet 发表于2014-01-04 19:38:10 浏览219 评论0

抢沙发发表评论

54 
55    /*
56     * 从网络上获取图片,如果图片在本地存在的话就直接拿,如果不存在再去服务器上下载图片
57     * 这里的path是图片的地址
58     */
59    public Uri getImageURI(String path, File cache) throws Exception {
60        String name = MD5.getMD5(path) + path.substring(path.lastIndexOf("."));
61        File file = new File(cache, name);
62        // 如果图片存在本地缓存目录,则不去服务器下载
63        if (file.exists()) {
64            return Uri.fromFile(file);//Uri.fromFile(path)这个方法能得到文件的URI
65        else {
66            // 从网络上获取图片
67            URL url = new URL(path);
68            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
69            conn.setConnectTimeout(5000);
70            conn.setRequestMethod("GET");
71            conn.setDoInput(true);
72            if (conn.getResponseCode() == 200) {
73 
74                InputStream is = conn.getInputStream();
75                FileOutputStream fos = new FileOutputStream(file);
76                byte[] buffer = new byte[1024];
77                int len = 0;
78                while ((len = is.read(buffer)) != -1) {
79                    fos.write(buffer, 0, len);
80                }
81                is.close();
82                fos.close();
83                // 返回一个URI对象
84                return Uri.fromFile(file);
85            }
86        }
87        return null;
88    }
89}

 

Serivce类中,注意以下几点
1.HttpURLConnection conn = (HttpURLConnection) url.openConnection();获取一个链接,从而进行通讯 2.怎么利用XxmlPullPaser类去解析XML,从而把数据封装成对象
3.getImageURI(String path, File cache) 这个方法具体实现
4.Uri.fromFile(file);这个方法能够直接返回一个Uri来
下面是自定义的Adapter类,
001public class MyContactAdapter extends BaseAdapter {
002 
003    protected static final int SUCCESS_GET_IMAGE = 0;
004    private Context context;
005    private List<Contact> contacts;
006    private File cache;
007    private LayoutInflater mInflater;
008 
009    // 自己定义的构造函数
010    public MyContactAdapter(Context context, List<Contact> contacts, File cache) {
011        this.context = context;
012        this.contacts = contacts;
013        this.cache = cache;
014 
015        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
016    }
017 
018    @Override
019    public int getCount() {
020        return contacts.size();
021    }
022 
023    @Override
024    public Object getItem(int position) {
025        return contacts.get(position);
026    }
027 
028    @Override
029    public long getItemId(int position) {
030        return position;
031    }
032 
033    @Override
034    public View getView(int position, View convertView, ViewGroup parent) {
035        // 1获取item,再得到控件
036        // 2 获取数据
037        // 3绑定数据到item
038        View view = null;
039        if (convertView != null) {
040            view = convertView;
041        else {
042            view = mInflater.inflate(R.layout.item, null);
043        }
044 
045        ImageView iv_header = (ImageView) view.findViewById(R.id.iv_header);
046        TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
047 
048        Contact contact = contacts.get(position);
049 
050        // 异步的加载图片 (线程池 + Handler ) ---> AsyncTask
051        asyncloadImage(iv_header, contact.image);
052        tv_name.setText(contact.name);
053 
054        return view;
055    }
056 
057    private void asyncloadImage(ImageView iv_header, String path) {
058        ContactService service = new ContactService();
059        AsyncImageTask task = new AsyncImageTask(service, iv_header);
060        task.execute(path);
061    }
062 
063    private final class AsyncImageTask extends AsyncTask<String, Integer, Uri> {
064 
065        private ContactService service;
066        private ImageView iv_header;
067 
068        public AsyncImageTask(ContactService service, ImageView iv_header) {
069            this.service = service;
070            this.iv_header = iv_header;
071        }
072 
073        // 后台运行的子线程子线程
074        @Override
075        protected Uri doInBackground(String... params) {
076            try {
077                return service.getImageURI(params[0], cache);
078            catch (Exception e) {
079                e.printStackTrace();
080            }
081            return null;
082        }
083 
084        // 这个放在在ui线程中执行
085        @Override
086        protected void onPostExecute(Uri result) {
087            super.onPostExecute(result);
088            // 完成图片的绑定
089            if (iv_header != null && result != null) {
090                iv_header.setImageURI(result);
091            }
092        }
093    }
 

群贤毕至

访客