1 package com.lixu.listviewrefresh;
2
3 import java.io.BufferedInputStream;
4 import java.io.ByteArrayOutputStream;
5 import java.io.InputStream;
6 import java.net.HttpURLConnection;
7 import java.net.URL;
8
9 import android.graphics.Bitmap;
10 import android.graphics.BitmapFactory;
11
12 public class Loadnetimage {
13 // 设置回调机制
14
15 private OnLoadnetimageListener mOnLoadnetimageListener;
16
17 public Loadnetimage() {
18
19 }
20
21 public interface OnLoadnetimageListener {
22 public void LoadnetimageListener(int count, int total);
23 }
24
25 public void SetLoadnetimageListener(OnLoadnetimageListener l) {
26 mOnLoadnetimageListener = l;
27 }
28
29
30
31 public Bitmap loadRawDataFromURL(String u) throws Exception {
32
33 URL url = new URL(u);
34 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
35 // 设置请求的一些常用的参数
36 conn.setReadTimeout(30000);
37 conn.setConnectTimeout(30000);
38 conn.setDoInput(true);
39 conn.connect();
40 // 获取图片总数
41 int total = conn.getContentLength();
42
43 InputStream is = conn.getInputStream();
44 BufferedInputStream bis = new BufferedInputStream(is);
45
46 ByteArrayOutputStream baos = new ByteArrayOutputStream();
47 // 缓存2KB
48 final int BUFFER_SIZE = 2 * 1024;
49 final int EOF = -1;
50
51 int count = 0;
52
53 int c;
54 byte[] buf = new byte[BUFFER_SIZE];
55
56 while (true) {
57 c = bis.read(buf);
58 if (c == EOF)
59 break;
60 // 每次累加到现在为止我们下载了多少数据,以便于后面计算已经下载的数据占了总数量的百分比
61 count = count + c;
62 // 发布最新的数据,更新随后的进度条显示进度使用
63 if (mOnLoadnetimageListener != null)
64 mOnLoadnetimageListener.LoadnetimageListener(count, total