android handler传递数据

起因:在android使用get请求获取验证码时需要重开一个线程,这就造成了我无法获取到从服务器后台返回的数据

解决方法:创建全局变量,将返回的数据解析后返回给handler,再在handler中将数据赋值给全局变量

部分代码如下:

private void getYzm(int money) {
        // TODO Auto-generated method stub
        String res = "";
        Date nowTime = new Date();
        SimpleDateFormat time = new SimpleDateFormat("yyMMddHHmm");
        String tel = PhoneUtils.getPhoneNumber(context);
        final String paramData = "imsi=" + imsi + "&imei=" + imei + "&tel="
                + tel + "&money=" + money + "&app="
                + app+ "&time=" + time.format(nowTime);
        String resultCode;
        
        new Thread(){
            public void run() {
                final String gainCode = HttpRequest.sendGet(url,
                        paramData);
            // url是请求验证码地址,是一个全局变量,这里没有列出来,paramData是请求参数,HttpRequest是一个工具类,下面发链接
                String resultCode;
                JSONObject dataJson;
                String orderid;
                try {
                    dataJson = new JSONObject(gainCode);
                    resultCode = dataJson.getString("resultCode");
                    orderid=dataJson.getString("orderid");
                    if("200000".equals(resultCode)){
                        msg = handler.obtainMessage();
                        Bundle bundle = new Bundle();
                        bundle.putString("orderid", orderid);// 将服务器返回的订单号传到Bundle中,,再通过handler传出
                        msg.setData(bundle);
                        msg.arg1 = 0;   // 0为获取验证码成功
                        handler.sendMessage(msg);
                    }else{
                        msg = handler.obtainMessage();
                        msg.arg1 = 1;  // -1为获取验证码失败
                        handler.sendMessage(msg);  
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }.start();
        
    }
    class MsgHandler extends Handler {
         private Activity activity;  
            public MsgHandler(Activity activity){  
                this.activity=activity;
            }
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.arg1) {  
            case 0:  
                dialog.show();
                Bundle bundle=msg.getData();
                orderid=bundle.getString("orderid");// 这里的orderid是一个全局变量
                break; 
            case 1:  
                showInfo("获取验证码失败!");  
                break;
            case 2:  
                showInfo("订购成功!");  
                break;
            case 3:  
                showInfo("提交验证码错误,请重新测试!");  
                break;  
            default:  
                break;  
            }  
            super.handleMessage(msg);
        }    

 

posted @ 2016-08-23 14:00  dtj007  阅读(10248)  评论(0编辑  收藏  举报