android 下载辅助类

最近公司有个项目需要做个手机终端,就开始了android的学习,之前没怎么接触过java和手机开发,有不足之处还请指正。

这次提交的是一个下载辅助类。

这个类里新建了一个线程,并进行下载操作,通过传入的 Handler 或者 Context 选择发送消息还是发送广播的形式进行消息传递。 因为小弟对android和java线程模型并不了解,所以结构上可能并不完善。

  1 public class FileDownloader {
2 static final String TAG = "FILE DOWNLOADER";
3 Thread thread = null;
4 Message msg = null;
5 Handler handler = null;
6 Context context = null;
7 String url;
8 String path;
9 String fileName;
10 int fileSize = 0;
11 int downloadPosition = 0;
12 public static final int ERROR = 0;
13 public static final int START = 1;
14 public static final int PROCESS = 2;
15 public static final int COMPLETE = 3;
16
17 public FileDownloader(String url,String path, String fileName, Handler handler, Context context) {
18 this.url = url;
19 this.path = path;
20 this.fileName = fileName;
21 this.handler = handler;
22 this.context = context;
23 CreateThread(url, path, fileName);
24 }
25
26 public void Start() {
27 thread.start();
28 }
29
30 public void Stop() {
31 thread.stop();
32 }
33
34 private void CreateThread(final String url, final String path, final String fileName) {
35 thread = new Thread(){
36 public void run() {
37 downFile(url, path, fileName);
38 }
39 };
40 }
41
42 private void downFile(String url, String path, String fileName) {
43 URL Url;
44 try {
45 if (url == null || url == "" || path == null || path == "" || fileName == null || fileName == "")
46 throw new RuntimeException("文件路径不完整");
47 Url = new URL(url);
48 HttpURLConnection urlConn = (HttpURLConnection)Url.openConnection();
49 //URLConnection urlConn = Url.openConnection();
50 urlConn.setRequestMethod("GET");
51 int code = urlConn.getResponseCode();
52 if (code == HttpURLConnection.HTTP_OK) {
53 urlConn.connect();
54 InputStream is = urlConn.getInputStream();
55 fileSize = urlConn.getContentLength();
56 if (fileSize < 1)
57 throw new RuntimeException("无法获取文件长度");
58 downloadPosition = 0;
59 sendStartMessage(fileSize);
60 File filePath = new File(path);
61 if (!filePath.exists())
62 filePath.mkdir();
63 FileOutputStream FOS = new FileOutputStream(filePath + "/" + fileName);
64 byte[] buffer = new byte[1024 * 4];
65 int numread = 0;
66 while ((numread = is.read(buffer)) != -1) {
67 FOS.write(buffer, 0, numread);
68 downloadPosition += numread;
69 sendProcessMessage(downloadPosition);
70 }
71 FOS.close();
72 is.close();
73 sendCompleteMessage();
74 } else {
75 sendErrorMessage("网络错误,返回值:" + code);
76 }
77 } catch (MalformedURLException e) {
78 sendErrorMessage("URL:" + e.getMessage());
79 } catch (IOException e) {
80 sendErrorMessage("IO:" + e.getMessage());
81 } catch (Exception e) {
82 sendErrorMessage("Runtime:" + e.getMessage());
83 }
84 }
85
86 private void sendStartMessage(int length) {
87 Log.d(TAG, "开始,文件长度:" + length);
88 if (handler != null) {
89 msg = new Message();
90 msg.what = FileDownloader.START;
91 msg.arg1 = fileSize;
92 msg.arg2 = downloadPosition;
93 handler.sendMessage(msg);
94 } else if (context != null) {
95 Intent intent = new Intent("willin.android.alarm.AlarmService");
96 intent.putExtra("type", FileDownloader.START);
97 intent.putExtra("length", length);
98 intent.putExtra("position", downloadPosition);
99 context.sendBroadcast(intent);
100 }
101 }
102
103 private void sendProcessMessage(int postion) {
104 Log.d(TAG, "已经下载:" + postion);
105
106 if (handler != null) {
107 msg = new Message();
108 msg.what = FileDownloader.PROCESS;
109 msg.arg1 = fileSize;
110 msg.arg2 = downloadPosition;
111 handler.sendMessage(msg);
112 }
113 /*
114 * 广播的情况下不发送中途消息
115 else if (context != null) {
116 Intent intent = new Intent("willin.android.alarm.AlarmService");
117 intent.putExtra("type", FileDownloader.PROCESS);
118 intent.putExtra("length", fileSize);
119 intent.putExtra("position", downloadPosition);
120 context.sendBroadcast(intent);
121 }
122 */
123 }
124
125 private void sendCompleteMessage() {
126 Log.d(TAG, "文件下载完成");
127 if (handler != null) {
128 msg = new Message();
129 msg.what = FileDownloader.COMPLETE;
130 msg.obj = fileName;
131 handler.sendMessage(msg);
132 } else if (context != null) {
133 Intent intent = new Intent("willin.android.alarm.AlarmService");
134 intent.putExtra("type", FileDownloader.COMPLETE);
135 intent.putExtra("msg", "下载完成");
136 Log.d(TAG, "发送下载完成 广播");
137 context.sendBroadcast(intent);
138 }
139 }
140
141 private void sendErrorMessage(String errorMsg) {
142 Log.d(TAG, "出现错误:" + errorMsg);
143 if (handler == null) {
144 msg = new Message();
145 msg.what = FileDownloader.ERROR;
146 msg.obj = errorMsg;
147 handler.sendMessage(msg);
148 } else if (context != null) {
149 Intent intent = new Intent("willin.android.alarm.AlarmService");
150 intent.putExtra("type", FileDownloader.ERROR);
151 intent.putExtra("msg", errorMsg);
152 Log.d(TAG, "发送下载出现错误 广播");
153 context.sendBroadcast(intent);
154 }
155 }
156 }

这样,你可以在Activity 中使用Handler 来处理这些消息:

public class MyActivity extends Activity {
private ProgressBar pb = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
     this.pb = (ProgressBar)findViewById(R.id.progressBar1);

Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new ButtonClickListener());
}

private class ButtonClickListener implements OnClickListener {
public void onClick(View arg0) {
FileDownloader fileDown = new FileDownloader(url, filePath, fileName, downloadHandler, null);
fileDown.Start();

}

private Handler downloadHandler = new Handler() { // 用于接收消息,处理进度条
@Override
public void handleMessage(Message msg) { // 接收到的消息,并且对接收到的消息进行处理
Log.d("DOWN", msg.what + "");
if (!Thread.currentThread().isInterrupted()) {
switch (msg.what) {
case FileDownloader.START:
pb.setMax(msg.arg1);
pb.setProgress(msg.arg2);
break;
case FileDownloader.PROCESS:
pb.setMax(msg.arg1);
pb.setProgress(msg.arg2);
break;
case FileDownloader.COMPLETE:
Toast.makeText(xmlActivity.this, msg.obj + " 下载完成!", 1).show(); // 完成提示
break;
case FileDownloader.ERROR:
String error = (String)msg.obj;
error = "下载失败:" + error;
Toast.makeText(xmlActivity.this, error, 1).show();
break;
}
}
super.handleMessage(msg);
}
};
}

或者注册一个 BroadcastReceiver,因为BroadcastReceiver需要绑定Activity或者Service,广播部分的代码就不再描述了。

同时showNotification()这样的自定义函数,还有一些变量的设置代码被我删掉了。

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "收到:" + intent.getAction());
if (intent.getAction().equals(ACTION)) {
//intent 里面是可以有数据的,所以这个应该是可以放到这边的. 使用 sendBroadCast 就行.
Log.d(TAG, "收到广播:" + intent.getAction() + "," + intent.getIntExtra("type", -1));
int type = intent.getIntExtra("type", -1);
switch (type) {
case FileDownloader.START:

break;
case FileDownloader.PROCESS:
//showNotification(context, "开始下载: type=" + type);
break;
case FileDownloader.COMPLETE:
showNotification(context, "下载完成");
break;
case FileDownloader.ERROR:
showNotification(context, "下载失败:" + intent.getStringExtra("msg"));
break;
default:
FileDownloader file = new FileDownloader(url, path, file, null, context);
file.Start();
break;
}


} else {

}
}

}




posted @ 2011-12-02 13:59  张鲸落  阅读(477)  评论(0编辑  收藏  举报