WEB开发网
开发学院手机开发Android 开发 Android的HTTP通信 XML解析和异步消息处理 阅读

Android的HTTP通信 XML解析和异步消息处理

 2010-02-03 19:10:00 来源:WEB开发网   
核心提示:while (readCount < fileSize && readNum != -1) {readNum = inputStream.read(buffer);if (readNum > -1) {outputStream.write(buffer);readCount = readCount + re

while (readCount < fileSize && readNum != -1) {

readNum = inputStream.read(buffer);

if (readNum > -1) {

outputStream.write(buffer);

readCount = readCount + readNum;

int percent = (int) (readCount * 100 / fileSize);

if (percent > prevPercent) {

// 发送下载进度信息

sendMessage(FILE_DOWNLOAD_UPDATE, percent,

readCount);

prevPercent = percent;

}

}

}

outputStream.close();

sendMessage(FILE_DOWNLOAD_COMPLETE, savePath);

} catch (Exception e) {

sendMessage(FILE_DOWNLOAD_ERROR, e);

Log.e("MyError", e.toString());

}

}

}).start();

}

// 读取指定 url 地址的响应内容

public void download(final String url) {

new Thread(new Runnable() {

public void run() {

try {

sendMessage(FILE_DOWNLOAD_CONNECT);

URL sourceUrl = new URL(url);

URLConnection conn = sourceUrl.openConnection();

conn.setConnectTimeout(3000);

BufferedReader reader = new BufferedReader(

new InputStreamReader(conn.getInputStream(),

HTTP.UTF_8));

String line = null;

StringBuffer content = new StringBuffer();

while ((line = reader.readLine()) != null) {

content.append(line);

}

reader.close();

sendMessage(FILE_DOWNLOAD_COMPLETE, content.toString());

} catch (Exception e) {

sendMessage(FILE_DOWNLOAD_ERROR, e);

Log.e("MyError", e.toString());

}

}

}).start();

}

// 向 Handler 发送消息

private void sendMessage(int what, Object obj) {

// 构造需要向 Handler 发送的消息

Message msg = mHandler.obtainMessage(what, obj);

上一页  3 4 5 6 7 8 9 10 11  下一页

Tags:Android HTTP 通信

编辑录入:coldstar [复制链接] [打 印]
赞助商链接