Android异步下载图片并且缓存图片到本地

Android开发中我们经常有这样的需求,从服务器上下载xml或者JSON类型的数据,其中包括一些图片资源,本demo模拟了这个需求,从网络上加载XML资源,其中包括图片,我们要做的解析XML里面的数据,并且把图片缓存到本地一个cache目录里面,并且用一个自定义的Adapter去填充到LIstView,demo运行效果见下图:


8aab384e-1764-32c7-b616-31ce5eb44760.png

        通过这个demo,要学会有一下几点

        1.怎么解析一个XML

        2.demo中用到的缓存图片到本地一个临时目录的思想是怎样的?

        3.AsyncTask类的使用,因为要去异步的加载数据,就必须开启线程,但是在开启线程的时有时候不能很好的控制线程的数量,线程数量太大的时候手机会很快被卡死 这里就采用AsynsTask类的去解决这个问题,这个类里面封装了线程池的技术,从而保证不会因开启过多的线程而消耗太多的资源

        4.本demo中的Handler类的使用情况 5.自定义adapter的使用

        下面是demo中的Activity。

Java代码
  1. public class MainActivity extends Activity {
  2.         protected static final int SUCCESS_GET_CONTACT = 0;
  3.         private ListView mListView;
  4.         private MyContactAdapter mAdapter;
  5.         private File cache;
  6.        
  7.         private Handler mHandler = new Handler(){
  8.                 public void handleMessage(android.os.Message msg) {
  9.                         if(msg.what == SUCCESS_GET_CONTACT){
  10.                                 List<Contact> contacts = (List<Contact>) msg.obj;
  11.                                 mAdapter = new MyContactAdapter(getApplicationContext(),contacts,cache);
  12.                                 mListView.setAdapter(mAdapter);
  13.                         }
  14.                 };
  15.         };
  16.        
  17.     @Override
  18.     public void onCreate(Bundle savedInstanceState) {
  19.         super.onCreate(savedInstanceState);
  20.         setContentView(R.layout.main);
  21.         
  22.         mListView = (ListView) findViewById(R.id.listview);
  23.         
  24.         //创建缓存目录,系统一运行就得创建缓存目录的,
  25.         cache = new File(Environment.getExternalStorageDirectory(), "cache");
  26.         
  27.         if(!cache.exists()){
  28.                 cache.mkdirs();
  29.         }
  30.         
  31.         //获取数据,主UI线程是不能做耗时操作的,所以启动子线程来做
  32.         new Thread(){
  33.                 public void run() {
  34.                         ContactService service = new ContactService();
  35.                         List<Contact> contacts = null;
  36.                                 try {
  37.                                         contacts = service.getContactAll();
  38.                                 } catch (Exception e) {
  39.                                         e.printStackTrace();
  40.                                 }
  41.                                 //子线程通过Message对象封装信息,并且用初始化好的,
  42.                                 //Handler对象的sendMessage()方法把数据发送到主线程中,从而达到更新UI主线程的目的
  43.                         Message msg = new Message();
  44.                         msg.what = SUCCESS_GET_CONTACT;
  45.                         msg.obj = contacts;
  46.                         mHandler.sendMessage(msg);
  47.                 };
  48.         }.start();
  49.     }
  50.    
  51.     @Override
  52.     protected void onDestroy() {
  53.             super.onDestroy();
  54.             //清空缓存
  55.             File[] files = cache.listFiles();
  56.             for(File file :files){
  57.                     file.delete();
  58.             }
  59.             cache.delete();
  60.     }
  61. }
复制代码
Activity中,注意以下几点,
        1.初始化了一个缓存目录,这个目录最好是应用开启就去创建好,为手续缓存图片做准备,在这里把数据存放在SDCard上
        2.要去服务器加载数据,这个耗时操作最好是去开启线程加载数据,加载完毕后去异步的更新UI线程,利用Handler机制能很好的解决这个问题,
        3.最后退出应用的时候,要删掉缓存目录和目录里面的数据,避免给手机制造很多的垃圾文件

        下面就是一个Service类了,
Java代码
  1. public class ContactService {

  2.         /*
  3.          * 从服务器上获取数据
  4.          */
  5.         public List<Contact> getContactAll() throws Exception {
  6.                 List<Contact> contacts = null;
  7.                 String Parth = "http://192.168.1.103:8080/myweb/list.xml";
  8.                 URL url = new URL(Parth);
  9.                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  10.                 conn.setConnectTimeout(3000);
  11.                 conn.setRequestMethod("GET");
  12.                 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
  13.                         InputStream is = conn.getInputStream();
  14.                         // 这里获取数据直接放在XmlPullParser里面解析
  15.                         contacts = xmlParser(is);
  16.                         return contacts;
  17.                 } else {
  18.                         return null;
  19.                 }
  20.         }

  21.         // 这里并没有下载图片下来,而是把图片的地址保存下来了
  22.         private List<Contact> xmlParser(InputStream is) throws Exception {
  23.                 List<Contact> contacts = null;
  24.                 Contact contact = null;
  25.                 XmlPullParser parser = Xml.newPullParser();
  26.                 parser.setInput(is, "UTF-8");
  27.                 int eventType = parser.getEventType();
  28.                 while ((eventType = parser.next()) != XmlPullParser.END_DOCUMENT) {
  29.                         switch (eventType) {
  30.                         case XmlPullParser.START_TAG:
  31.                                 if (parser.getName().equals("contacts")) {
  32.                                         contacts = new ArrayList<Contact>();
  33.                                 } else if (parser.getName().equals("contact")) {
  34.                                         contact = new Contact();
  35.                                         contact.setId(Integer.valueOf(parser.getAttributeValue(0)));
  36.                                 } else if (parser.getName().equals("name")) {
  37.                                         contact.setName(parser.nextText());
  38.                                 } else if (parser.getName().equals("image")) {
  39.                                         contact.setImage(parser.getAttributeValue(0));
  40.                                 }
  41.                                 break;

  42.                         case XmlPullParser.END_TAG:
  43.                                 if (parser.getName().equals("contact")) {
  44.                                         contacts.add(contact);
  45.                                 }
  46.                                 break;
  47.                         }
  48.                 }
  49.                 return contacts;
  50.         }

  51.         /*
  52.          * 从网络上获取图片,如果图片在本地存在的话就直接拿,如果不存在再去服务器上下载图片
  53.          * 这里的path是图片的地址
  54.          */
  55.         public Uri getImageURI(String path, File cache) throws Exception {
  56.                 String name = MD5.getMD5(path) + path.substring(path.lastIndexOf("."));
  57.                 File file = new File(cache, name);
  58.                 // 如果图片存在本地缓存目录,则不去服务器下载
  59.                 if (file.exists()) {
  60.                         return Uri.fromFile(file);//Uri.fromFile(path)这个方法能得到文件的URI
  61.                 } else {
  62.                         // 从网络上获取图片
  63.                         URL url = new URL(path);
  64.                         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  65.                         conn.setConnectTimeout(5000);
  66.                         conn.setRequestMethod("GET");
  67.                         conn.setDoInput(true);
  68.                         if (conn.getResponseCode() == 200) {

  69.                                 InputStream is = conn.getInputStream();
  70.                                 FileOutputStream fos = new FileOutputStream(file);
  71.                                 byte[] buffer = new byte[1024];
  72.                                 int len = 0;
  73.                                 while ((len = is.read(buffer)) != -1) {
  74.                                         fos.write(buffer, 0, len);
  75.                                 }
  76.                                 is.close();
  77.                                 fos.close();
  78.                                 // 返回一个URI对象
  79.                                 return Uri.fromFile(file);
  80.                         }
  81.                 }
  82.                 return null;
  83.         }
  84. }
复制代码
Serivce类中,注意以下几点
        1.HttpURLConnection conn = (HttpURLConnection) url.openConnection();获取一个链接,从而进行通讯        2.怎么利用XxmlPullPaser类去解析XML,从而把数据封装成对象
        3.getImageURI(String path, File cache) 这个方法具体实现
        4.Uri.fromFile(file);这个方法能够直接返回一个Uri来

        下面是自定义的Adapter类,
Java代码
  1. public class MyContactAdapter extends BaseAdapter {

  2.         protected static final int SUCCESS_GET_IMAGE = 0;
  3.         private Context context;
  4.         private List<Contact> contacts;
  5.         private File cache;
  6.         private LayoutInflater mInflater;

  7.         // 自己定义的构造函数
  8.         public MyContactAdapter(Context context, List<Contact> contacts, File cache) {
  9.                 this.context = context;
  10.                 this.contacts = contacts;
  11.                 this.cache = cache;

  12.                 mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  13.         }

  14.         @Override
  15.         public int getCount() {
  16.                 return contacts.size();
  17.         }

  18.         @Override
  19.         public Object getItem(int position) {
  20.                 return contacts.get(position);
  21.         }

  22.         @Override
  23.         public long getItemId(int position) {
  24.                 return position;
  25.         }

  26.         @Override
  27.         public View getView(int position, View convertView, ViewGroup parent) {
  28.                 // 1获取item,再得到控件
  29.                 // 2 获取数据
  30.                 // 3绑定数据到item
  31.                 View view = null;
  32.                 if (convertView != null) {
  33.                         view = convertView;
  34.                 } else {
  35.                         view = mInflater.inflate(R.layout.item, null);
  36.                 }

  37.                 ImageView iv_header = (ImageView) view.findViewById(R.id.iv_header);
  38.                 TextView tv_name = (TextView) view.findViewById(R.id.tv_name);

  39.                 Contact contact = contacts.get(position);

  40.                 // 异步的加载图片 (线程池 + Handler ) ---> AsyncTask
  41.                 asyncloadImage(iv_header, contact.image);
  42.                 tv_name.setText(contact.name);

  43.                 return view;
  44.         }

  45.         private void asyncloadImage(ImageView iv_header, String path) {
  46.                 ContactService service = new ContactService();
  47.                 AsyncImageTask task = new AsyncImageTask(service, iv_header);
  48.                 task.execute(path);
  49.         }

  50.         private final class AsyncImageTask extends AsyncTask<String, Integer, Uri> {

  51.                 private ContactService service;
  52.                 private ImageView iv_header;

  53.                 public AsyncImageTask(ContactService service, ImageView iv_header) {
  54.                         this.service = service;
  55.                         this.iv_header = iv_header;
  56.                 }

  57.                 // 后台运行的子线程子线程
  58.                 @Override
  59.                 protected Uri doInBackground(String... params) {
  60.                         try {
  61.                                 return service.getImageURI(params[0], cache);
  62.                         } catch (Exception e) {
  63.                                 e.printStackTrace();
  64.                         }
  65.                         return null;
  66.                 }

  67.                 // 这个放在在ui线程中执行
  68.                 @Override
  69.                 protected void onPostExecute(Uri result) {
  70.                         super.onPostExecute(result);
  71.                         // 完成图片的绑定
  72.                         if (iv_header != null && result != null) {
  73.                                 iv_header.setImageURI(result);
  74.                         }
  75.                 }
  76.         }

  77.         /**
  78.          * 采用普通方式异步的加载图片
  79.          */
  80.         /*private void asyncloadImage(final ImageView iv_header, final String path) {
  81.                 final Handler mHandler = new Handler() {
  82.                         @Override
  83.                         public void handleMessage(Message msg) {
  84.                                 super.handleMessage(msg);
  85.                                 if (msg.what == SUCCESS_GET_IMAGE) {
  86.                                         Uri uri = (Uri) msg.obj;
  87.                                         if (iv_header != null && uri != null) {
  88.                                                 iv_header.setImageURI(uri);
  89.                                         }

  90.                                 }
  91.                         }
  92.                 };
  93.                 // 子线程,开启子线程去下载或者去缓存目录找图片,并且返回图片在缓存目录的地址
  94.                 Runnable runnable = new Runnable() {
  95.                         @Override
  96.                         public void run() {
  97.                                 ContactService service = new ContactService();
  98.                                 try {
  99.                                         //这个URI是图片下载到本地后的缓存目录中的URI
  100.                                         Uri uri = service.getImageURI(path, cache);
  101.                                         Message msg = new Message();
  102.                                         msg.what = SUCCESS_GET_IMAGE;
  103.                                         msg.obj = uri;
  104.                                         mHandler.sendMessage(msg);
  105.                                 } catch (Exception e) {
  106.                                         e.printStackTrace();
  107.                                 }
  108.                         }
  109.                 };
  110.                 new Thread(runnable).start();
  111.         }*/
  112. }
复制代码
自定义Adapter中,我们要注意 AsyncImageTask这个类继承了AsyncTask类,AsyncTask是Android中常用来做异步任务的类,对线程池进行了封装,详细分析稍后再贴出一篇Blog。

        下面是我们从服务器上获取并且解析的Xml文件
Xml代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <contacts>
  3.         <contact id="1">
  4.                 <name>张飞</name>
  5.                 <image src="http://192.168.1.103:8080/mymyweb/images/1.gif"/>
  6.         </contact>
  7.         <contact id="2">
  8.                 <name>博文</name>
  9.                 <image src="http://192.168.1.103:8080/myweb/images/2.gif"/>
  10.         </contact>       
  11.         <contact id="3">
  12.                 <name>张天佑</name>
  13.                 <image src="http://192.168.1.103:8080/myweb/images/3.gif"/>
  14.         </contact>               
  15.         <contact id="4">
  16.                 <name>松德</name>
  17.                 <image src="http://192.168.1.103:8080/myweb/images/4.gif"/>
  18.         </contact>               
  19.         <contact id="5">
  20.                 <name>赵薇</name>
  21.                 <image src="http://192.168.1.103:8080/myweb/images/5.gif"/>
  22.         </contact>
  23.         <contact id="6">
  24.                 <name>李静</name>
  25.                 <image src="http://192.168.1.103:8080/myweb/images/6.gif"/>
  26.         </contact>       
  27.         <contact id="7">
  28.                 <name>李明</name>
  29.                 <image src="http://192.168.1.103:8080/myweb/images/7.gif"/>
  30.         </contact>               
  31.         <contact id="8">
  32.                 <name>黎明</name>
  33.                 <image src="http://192.168.1.103:8080/myweb/images/8.gif"/>
  34.         </contact>               
  35.        
  36.         <contact id="9">
  37.                 <name>秦桧</name>
  38.                 <image src="http://192.168.1.103:8080/myweb/images/9.gif"/>
  39.         </contact>
  40.         <contact id="10">
  41.                 <name>朱德</name>
  42.                 <image src="http://192.168.1.103:8080/myweb/images/10.gif"/>
  43.         </contact>       
  44.         <contact id="11">
  45.                 <name>冯巩</name>
  46.                 <image src="http://192.168.1.103:8080/myweb/images/11.gif"/>
  47.         </contact>               
  48.         <contact id="12">
  49.                 <name>dylan</name>
  50.                 <image src="http://192.168.1.103:8080/myweb/images/12.gif"/>
  51.         </contact>               
  52.         <contact id="13">
  53.                 <name>黄单</name>
  54.                 <image src="http://192.168.1.103:8080/myweb/images/13.gif"/>
  55.         </contact>
  56.         <contact id="14">
  57.                 <name>含蕊</name>
  58.                 <image src="http://192.168.1.103:8080/myweb/images/14.gif"/>
  59.         </contact>       
  60.         <contact id="15">
  61.                 <name>欣琪</name>
  62.                 <image src="http://192.168.1.103:8080/myweb/images/15.jpg"/>
  63.         </contact>               
  64.         <contact id="16">
  65.                 <name>李忠华</name>
  66.                 <image src="http://192.168.1.103:8080/myweb/images/16.jpg"/>
  67.         </contact>       
  68.         <contact id="17">
  69.                 <name>方产员</name>
  70.                 <image src="http://192.168.1.103:8080/myweb/images/17.jpg"/>
  71.         </contact>               
  72.         <contact id="18">
  73.                 <name>张光</name>
  74.                 <image src="http://192.168.1.103:8080/myweb/images/18.jpg"/>
  75.         </contact>       
  76. </contacts>
复制代码
        本demo中为了安全起见,还对下载下来的图片的文件名进行了MD5加密,下面是MD5加密的代码,
Java代码
  1. public class MD5 {

  2.         public static String getMD5(String content) {
  3.                 try {
  4.                         MessageDigest digest = MessageDigest.getInstance("MD5");
  5.                         digest.update(content.getBytes());
  6.                         return getHashString(digest);
  7.                        
  8.                 } catch (NoSuchAlgorithmException e) {
  9.                         e.printStackTrace();
  10.                 }
  11.                 return null;
  12.         }
  13.        
  14.     private static String getHashString(MessageDigest digest) {
  15.         StringBuilder builder = new StringBuilder();
  16.         for (byte b : digest.digest()) {
  17.             builder.append(Integer.toHexString((b >> 4) & 0xf));
  18.             builder.append(Integer.toHexString(b & 0xf));
  19.         }
  20.         return builder.toString();
  21.     }
  22. }
复制代码
以上省略了Contact.java这个domain类,通过这个demo,可以看出Android中会经常需要进行异步任务的处理,所以我们会常常用到自己手动开启线程,handler机制,或者AsyncTask类等手段来保证应用的性能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值