WEB开发网
开发学院手机开发Android 开发 Android线程交互(Handler+Thread 和 AsyncTask)... 阅读

Android线程交互(Handler+Thread 和 AsyncTask)

 2010-09-10 00:49:00 来源:WEB开发网   
核心提示:}// 返回结果return s;} catch (Exception e) {e.printStackTrace();}return null;}}package com.ophone.network;//这里为了节省篇幅,忽略了import项public class NetworkActivity extends

}

// 返回结果

return s;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}

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());

}

// 返回结果

return s;

} catch (Exception e) {

上一页  1 2 3 4 5 6 7  下一页

Tags:Android 线程 交互

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