handler用於多線程json
handler必須存在於主線程中多線程
界面ui更新必須在handler中異步
對於異步,對於每個任務咱們都要建立一個線程ide
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"); }