android异步下载图片缓存到sdcard
从网络上加载XML资源,其中包括图片,我们要做的解析XML里面的数据,并且把图片缓存到本地一个cache目录里面,并且用一个自定义的Adapter去填充到LIstView:
对象类
public class Contact { int id; String image; String name; public Contact() { super(); } public Contact(int id, String image, String name) { this.id = id; this.image = image; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
service类
public class ContactService { /* * 从服务器上获取数据 */ public List<Contact> getContactAll() throws Exception { List<Contact> contacts = null; String Parth = "http://10.0.2.2:8080/AsyncTaskTest/list.xml"; URL url = new URL(Parth); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); // 这里获取数据直接放在XmlPullParser里面解析 contacts = xmlParser(is); return contacts; } else { return null; } } // 这里并没有下载图片下来,而是把图片的地址保存下来了 private List<Contact> xmlParser(InputStream is) throws Exception { List<Contact> contacts = null; Contact contact = null; XmlPullParser parser = Xml.newPullParser(); parser.setInput(is, "UTF-8"); int eventType = parser.getEventType(); while ((eventType = parser.next()) != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: if (parser.getName().equals("contacts")) { contacts = new ArrayList<Contact>(); } else if (parser.getName().equals("contact")) { contact = new Contact(); contact.setId(Integer.valueOf(parser.getAttributeValue(0))); } else if (parser.getName().equals("name")) { contact.setName(parser.nextText()); } else if (parser.getName().equals("image")) { contact.setImage(parser.getAttributeValue(0)); } break; case XmlPullParser.END_TAG: if (parser.getName().equals("contact")) { contacts.add(contact); } break; } } return contacts; } /* * 从网络上获取图片,如果图片在本地存在的话就直接拿,如果不存在再去服务器上下载图片 * 这里的path是图片的地址 */ public Uri getImageURI(String path, File cache) throws Exception { String name = MD5.getMD5(path) + path.substring(path.lastIndexOf(".")); File file = new File(cache, name); // 如果图片存在本地缓存目录,则不去服务器下载 if (file.exists()) { return Uri.fromFile(file);//Uri.fromFile(path)这个方法能得到文件的URI } else { // 从网络上获取图片 URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); conn.setDoInput(true); if (conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); FileOutputStream fos = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } is.close(); fos.close(); // 返回一个URI对象 return Uri.fromFile(file); } } return null; } }
自定义Adapter
public class ImageAdapter extends BaseAdapter { protected static final int SUCCESS_GET_IMAGE = 0; private Context context; private List<Contact> contacts; private File cache; private LayoutInflater mInflater; // 自己定义的构造函数 public ImageAdapter(Context context, List<Contact> contacts, File cache) { this.context = context; this.contacts = contacts; this.cache = cache; mInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return contacts.size(); } @Override public Object getItem(int position) { return contacts.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // 1获取item,再得到控件 // 2 获取数据 // 3绑定数据到item View view = null; if (convertView != null) { view = convertView; } else { view = mInflater.inflate(R.layout.item, null); } ImageView iv_header = (ImageView) view.findViewById(R.id.imageView); TextView tv_name = (TextView) view.findViewById(R.id.textView); Contact contact = contacts.get(position); // 异步的加载图片 (线程池 + Handler ) ---> AsyncTask asyncloadImage(iv_header, contact.image); tv_name.setText(contact.name); return view; } private void asyncloadImage(ImageView iv_header, String path) { ContactService service = new ContactService(); AsyncImageTask task = new AsyncImageTask(service, iv_header); task.execute(path); } private final class AsyncImageTask extends AsyncTask<String, Integer, Uri> { private ContactService service; private ImageView iv_header; public AsyncImageTask(ContactService service, ImageView iv_header) { this.service = service; this.iv_header = iv_header; } // 后台运行的子线程子线程 @Override protected Uri doInBackground(String... params) { try { return service.getImageURI(params[0], cache); } catch (Exception e) { e.printStackTrace(); } return null; } // 这个放在在ui线程中执行 @Override protected void onPostExecute(Uri result) { super.onPostExecute(result); // 完成图片的绑定 if (iv_header != null && result != null) { iv_header.setImageURI(result); } } } }
public class MainActivity extends Activity { protected static final int SUCCESS_GET_CONTACT = 0; private ListView mListView; private ImageAdapter mAdapter; private File cache; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mListView = (ListView) findViewById(R.id.listView); //创建缓存目录,系统一运行就得创建缓存目录的, cache = new File(Environment.getExternalStorageDirectory(), "cache"); if(!cache.exists()){ cache.mkdirs(); } //获取数据,主UI线程是不能做耗时操作的,所以启动子线程来做 new Thread(){ public void run() { ContactService service = new ContactService(); List<Contact> contacts = null; try { contacts = service.getContactAll(); } catch (Exception e) { e.printStackTrace(); } //子线程通过Message对象封装信息,并且用初始化好的, //Handler对象的sendMessage()方法把数据发送到主线程中,从而达到更新UI主线程的目的 Message msg = new Message(); msg.what = SUCCESS_GET_CONTACT; msg.obj = contacts; mHandler.sendMessage(msg); }; }.start(); } private Handler mHandler = new Handler(){ public void handleMessage(android.os.Message msg) { if(msg.what == SUCCESS_GET_CONTACT){ List<Contact> contacts = (List<Contact>) msg.obj; mAdapter = new ImageAdapter(getApplicationContext(),contacts,cache); mListView.setAdapter(mAdapter); } }; }; @Override protected void onDestroy() { super.onDestroy(); //清空缓存 File[] files = cache.listFiles(); for(File file :files){ file.delete(); } cache.delete(); } }
服务器xml文件
<?xml version="1.0" encoding="UTF-8"?> <contacts> <contact id="1"> <name>图标1</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/1.png" /> </contact> <contact id="2"> <name>图标2</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/2.png" /> </contact> <contact id="3"> <name>图标3</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/3.png" /> </contact> <contact id="4"> <name>图标4</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/4.png" /> </contact> <contact id="5"> <name>图标5</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/5.png" /> </contact> <contact id="6"> <name>图标6</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/6.png" /> </contact> <contact id="7"> <name>图标7</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/7.png" /> </contact> <contact id="8"> <name>图标8</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/8.png" /> </contact> <contact id="9"> <name>图标9</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/9.png" /> </contact> <contact id="10"> <name>图标10</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/10.png" /> </contact> <contact id="11"> <name>图标11</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/11.png" /> </contact> <contact id="12"> <name>图标12</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/12.png" /> </contact> <contact id="13"> <name>图标13</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/13.png" /> </contact> <contact id="14"> <name>图标14</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/14.png" /> </contact> <contact id="15"> <name>图标15</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/15.png" /> </contact> <contact id="16"> <name>图标16</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/16.png" /> </contact> <contact id="17"> <name>图标17</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/17.png" /> </contact> <contact id="18"> <name>图标18</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/18.png" /> </contact> <contact id="19"> <name>图标19</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/19.png" /> </contact> <contact id="20"> <name>图标20</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/20.png" /> </contact> <contact id="21"> <name>图标21</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/1.png" /> </contact> <contact id="22"> <name>图标22</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/2.png" /> </contact> <contact id="23"> <name>图标23</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/3.png" /> </contact> <contact id="24"> <name>图标24</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/4.png" /> </contact> <contact id="25"> <name>图标25</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/5.png" /> </contact> <contact id="26"> <name>图标26</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/6.png" /> </contact> <contact id="27"> <name>图标27</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/7.png" /> </contact> <contact id="28"> <name>图标28</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/8.png" /> </contact> <contact id="29"> <name>图标29</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/9.png" /> </contact> <contact id="30"> <name>图标30</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/10.png" /> </contact> <contact id="31"> <name>图标31</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/11.png" /> </contact> <contact id="32"> <name>图标32</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/12.png" /> </contact> <contact id="33"> <name>图标33</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/13.png" /> </contact> <contact id="34"> <name>图标34</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/14.png" /> </contact> <contact id="35"> <name>图标35</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/15.png" /> </contact> <contact id="36"> <name>图标36</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/16.png" /> </contact> <contact id="37"> <name>图标37</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/17.png" /> </contact> <contact id="38"> <name>图标38</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/18.png" /> </contact> <contact id="39"> <name>图标39</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/19.png" /> </contact> <contact id="40"> <name>图标40</name> <image src="http://192.168.34.20:8080/AsyncTaskTest/image/20.png" /> </contact> </contacts>
AsyncTask.zip AsyncTaskTest.zip