handler用于多线程
handler必须存在于主线程中
界面ui更新必须在handler中
对于异步,对于每一个任务我们都要创建一个线程
Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); String response = (String) msg.obj; Log.e("msg handler1", String.valueOf(msg.what)); switch (msg.what) { case 1: try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } news_flag.setText(response); break; case 2: try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } meetings_flag.setText(response); break; } } };
private void loginPost(final String url, final String flag) { new Thread(new Runnable() { @Override public void run() { HttpClient client = new DefaultHttpClient(); HttpPost post=new HttpPost(url); List<NameValuePair> params=new ArrayList<NameValuePair>(); JSONObject obj= new JSONObject(); try { obj.put("flag", flag); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } params.add(new BasicNameValuePair("num",obj.toString())); try { post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); HttpResponse response = client.execute(post); // 判断请求是否成功 if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String out; if (entity != null) { out = EntityUtils.toString(entity, "utf-8"); JSONObject json=null; try { json=new JSONObject(out); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 在子线程中将Message对象发出去 Message message = new Message(); try { Log.e("1.........",json.getString("flag") ); if(json.getString("flag").equals("news")){ message.what = 1; message.obj=json.getString("value"); handler.sendMessage(message); }else if(json.getString("flag").equals("meetings")){ message.what = 2;// 请求的地址是访问会议资讯地址 message.obj=json.getString("value"); handler.sendMessage(message); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }// 请求的地址是访问新闻资讯地址 } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}).start(); }
public void onResume() { // TODO Auto-generated method stub super.onResume(); loginPost(url+"/news", "news"); loginPost(url+"/meetings", "meetings"); }