從網絡上加載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