Android的HTTP通信 XML解析和异步消息处理
2010-02-03 19:10:00 来源:WEB开发网项目上点右键 -> Build Path -> Add Libraries -> User Library -> User Libraries -> New -> 为类库起个名字 -> 选中这个类库 -> Add JARs 导入 Android 的 jar 包
项目上点右键 -> Build Path -> Add Libraries -> User Library -> 选择 Android 库
DownloadManagerAsync.java
代码
package webabcd.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.protocol.HTTP;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
// 以一个实例,即异步下载,来演示 Android 的异步消息处理(用 Handler 的方式)
public class DownloadManagerAsync {
public DownloadManagerAsync() {
}
// 实例化自定义的 Handler
EventHandler mHandler = new EventHandler(this);
// 按指定 url 地址下载文件到指定路径
public void download(final String url, final String savePath) {
new Thread(new Runnable() {
public void run() {
try {
sendMessage(FILE_DOWNLOAD_CONNECT);
URL sourceUrl = new URL(url);
URLConnection conn = sourceUrl.openConnection();
InputStream inputStream = conn.getInputStream();
int fileSize = conn.getContentLength();
File savefile = new File(savePath);
if (savefile.exists()) {
savefile.delete();
}
savefile.createNewFile();
FileOutputStream outputStream = new FileOutputStream(
savePath, true);
byte[] buffer = new byte[1024];
int readCount = 0;
int readNum = 0;
int prevPercent = 0;
更多精彩
赞助商链接