Android线程交互(Handler+Thread 和 AsyncTask)
2010-09-10 00:49:00 来源:WEB开发网为什么需要线程
假设需要开发一个联网应用程序,需要从一个网址抓取网页内容,这里读取的网页地址是笔者在本地机器上自己建立的服务器地址。当然在读取网页内容的时候,可以使用HttpClient提供的API,但是这并不是本文的介绍重点。缺乏联网程序开发经验的程序员可能写出下面的代码。
package com.ophone.network;
//这里为了节省篇幅,忽略了import项
public class NetworkActivity extends Activity {
// 显示任务的执行状态和返回结果
private TextView message;
private Button open;
private EditText url;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
message = (TextView) findViewById(R.id.message);
url = (EditText) findViewById(R.id.url);
open = (Button) findViewById(R.id.open);
open.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
connect();
}
});
}
private String connect() {
try {
HttpClient client = new DefaultHttpClient();
// params[0]代表连接的url
HttpGet get = new HttpGet(url.getText().toString());
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
InputStream is = entity.getContent();
String s = null;
if (is != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[128];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
baos.write(buf, 0, ch);
count += ch;
// 为了在模拟器中清楚地看到进度,让线程休眠1000ms
Thread.sleep(50000);
}
s = new String(baos.toByteArray());
更多精彩
赞助商链接