學習圖片下載並保存

public class MainActivity extends Activity {
    protected static final int SUCCESS_GET_CONTACT = 0;
    private ListView mListView;
    private MyContactAdapter mAdapter;
    private File cache;
   
    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 MyContactAdapter(getApplicationContext(),contacts,cache);
                mListView.setAdapter(mAdapter);
            }
        };
    };
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.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();
    }
   
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清空緩存
        File[] files = cache.listFiles();
        for(File file :files){
            file.delete();
        }
        cache.delete();
    }
}
public class ContactService {

    /*
     * 從服務器上獲取數據
     */
    public List<Contact> getContactAll() throws Exception {
        List<Contact> contacts = null;
        String Parth = "http://192.168.1.103:8080/myweb/list.xml";
        URL url = new URL(Parth);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(3000);
        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;
    }
}
 public class MyContactAdapter extends BaseAdapter {

    protected static final int SUCCESS_GET_IMAGE = 0;
    private Context context;
    private List<Contact> contacts;
    private File cache;
    private LayoutInflater mInflater;

    // 本身定義的構造函數
    public MyContactAdapter(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.iv_header);
        TextView tv_name = (TextView) view.findViewById(R.id.tv_name);

        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);
            }
        }
    }

    /**
     * 採用普通方式異步的加載圖片
     */
    /*private void asyncloadImage(final ImageView iv_header, final String path) {
        final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == SUCCESS_GET_IMAGE) {
                    Uri uri = (Uri) msg.obj;
                    if (iv_header != null && uri != null) {
                        iv_header.setImageURI(uri);
                    }

                }
            }
        };
        // 子線程,開啓子線程去下載或者去緩存目錄找圖片,而且返回圖片在緩存目錄的地址
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                ContactService service = new ContactService();
                try {
                    //這個URI是圖片下載到本地後的緩存目錄中的URI
                    Uri uri = service.getImageURI(path, cache);
                    Message msg = new Message();
                    msg.what = SUCCESS_GET_IMAGE;
                    msg.obj = uri;
                    mHandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable).start();
    }*/
}
public class MD5 {
    public static String getMD5(String content) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(content.getBytes());
            return getHashString(digest);
           
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
   
    private static String getHashString(MessageDigest digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest.digest()) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString(b & 0xf));
        }
        return builder.toString();
    }
}
相關文章
相關標籤/搜索