标签:android handler message 消息机制
在上一篇文章《Android AsyncTask异步任务》中我们介绍了如何使用AsyncTask异步处理网络通信和UI更新。在本文中将使用Handler消息机制来异步处理网络通信和UI更新。<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="城市:" android:textSize="23sp" /> <EditText android:id="@+id/city" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="3" android:inputType="text" /> </LinearLayout> <Button android:id="@+id/query" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查询" android:textSize="23sp" /> <TextView android:id="@+id/result" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
package com.rainsong.handlerdemo; import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private static final String JUHE_URL_ENVIRONMENT_AIR_PM = "http://web.juhe.cn:8080/environment/air/pm"; private static final String JUHE_APPKEY = "你申请的APPKEY值"; private static final int MSG_SUCCESS = 0; private static final int MSG_FAILURE = 1; EditText et_city; Button btn_query; TextView tv_result; String city; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case MSG_SUCCESS: tv_result.setText((String)msg.obj); break; case MSG_FAILURE: Toast.makeText(MainActivity.this, "查询失败", Toast.LENGTH_LONG).show(); tv_result.setText(""); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_city = (EditText)findViewById(R.id.city); tv_result = (TextView)findViewById(R.id.result); btn_query = (Button)findViewById(R.id.query); btn_query.setOnClickListener(new OnClickListener() { public void onClick(View view) { city = et_city.getText().toString(); if (city.length() < 1) { Toast.makeText(MainActivity.this, "请输入城市名", Toast.LENGTH_LONG).show(); tv_result.setText(""); return; } new Thread() { public void run() { ArrayList<NameValuePair> headerList = new ArrayList<NameValuePair>(); headerList.add(new BasicNameValuePair("Content-Type", "text/html; charset=utf-8")); String targetUrl = JUHE_URL_ENVIRONMENT_AIR_PM; ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>(); paramList.add(new BasicNameValuePair("key", JUHE_APPKEY)); paramList.add(new BasicNameValuePair("dtype", "json")); paramList.add(new BasicNameValuePair("city", city)); for (int i = 0; i < paramList.size(); i++) { NameValuePair nowPair = paramList.get(i); String value = nowPair.getValue(); try { value = URLEncoder.encode(value, "UTF-8"); } catch (Exception e) { } if (i == 0) { targetUrl += ("?" + nowPair.getName() + "=" + value); } else { targetUrl += ("&" + nowPair.getName() + "=" + value); } } HttpGet httpRequest = new HttpGet(targetUrl); try { for (int i = 0; i < headerList.size(); i++) { httpRequest.addHeader(headerList.get(i).getName(), headerList.get(i).getValue()); } HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == 200) { String strResult = EntityUtils.toString(httpResponse.getEntity()); mHandler.obtainMessage(MSG_SUCCESS, strResult).sendToTarget(); return; } else { mHandler.obtainMessage(MSG_FAILURE).sendToTarget(); return; } } catch (IOException e) { e.printStackTrace(); } } }.start(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
Sends this Message to the Handler specified by getTarget().
标签:android handler message 消息机制
原文地址:http://blog.csdn.net/hantangsongming/article/details/42172917