android跨线程通讯可以使用android.os.Handler-android.os.Message这两类对象完成。
public static void getResultForHttpGet(final String url,final Handler handler) throws ClientProtocolException, IOException{
new Thread(){
@Override
public void run() {
String result="";
HttpGet httpGet=new HttpGet(url);//
HttpResponse response=new DefaultHttpClient().execute(httpGet);
int statusCode=response.getStatusLine().getStatusCode();
if(statusCode==200){
HttpEntity entity=response.getEntity();
result=EntityUtils.toString(entity, HTTP.UTF_8);
}
Message msg=handler.obtainMessage(statusCode, result);
msg.sendToTarget();
}
}.start();
}
原获得返回值之后的代码写到 handler参数对象重写的handleMessage方法中,如果直接发起请求的类不是Activity,可以自定义接口来将信息传递给Activity。
private Handler handler1 = new MyHandler();
private class MyHandler extends Handler{
public void handleMessage(Message msg) {
int statusCode = msg.what;
if(statusCode==200){
String result = msg.obj.toString();
//do your business
}else{
// throw exception or show error message
}
}
};
private Handler handler2 = new MyHandler2();
private class MyHandler2 extends Handler{
public void handleMessage(Message msg) {
int statusCode = msg.what;
if(statusCode==200){
String result = msg.obj.toString();
//do other business
}else{
// throw exception or show error message
}
}
};
此外handler的post(Runnable r)方法也是跨线程操作的重要方法
//注意,若如此做,在Activity中构建的handler对象在Activity销毁后仍然有可能接收消息并执行handleMessage方法,应设法避免。关键字:handler内存泄漏