zoukankan      html  css  js  c++  java
  • android HttpGet 另开线程获取网络数据问题

    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内存泄漏
  • 相关阅读:
    学会用google吧,,,
    HDU 2120 Ice_cream's world I
    ZOJ 3471 Most Powerful (状压DP)
    POJ 2192 Zipper
    我的闪存汇总
    Python For Delphi更好地协同(续)
    Python For Delphi更好地协同
    官方的正则表达式组件 RegularExpressions : 基本应用(转自万一博客)
    Thread: DataSnap detect disgraceful disconnect
    window7下安装IPython
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/4742301.html
Copyright © 2011-2022 走看看