在Android的应用启动时,会创建一个主线程,主线程会创建一个消息队列来处理各种消息。当你创建子线程时,你可以在你的子线程中拿到父线程中创建的Handler 对象,就可以通过该对象向父线程的消息队列发送消息了。由于Android要求在UI线程中更新界面,因此,可以通过该方法在其它线程中更新界面。
每个handler 对应一个线程 thread , 在子线程中 handler 发送的消息会进入到 Message Queue当中去,由 looper 再来分发给 Handler 处理。
我们创建的Service、Activity以及Broadcast均是一个主线程处理,这里我们可以理解为UI线程。但是在操作一些耗时操作时,比如I/O读写的大文件读写,数据库操作以及网络下载需要很长时间,为了不阻塞用户界面,出现ANR(Application Not Responding)的响应提示窗口,这个时候我们可以考虑使用Thread线程来解决。
使用以下链接去浏览器中访问:
http://api.k780.com:88/app=phone.get&phone=18566669900
&appkey=14114&sign=ede788f7bf8d0678e281f660654ef995&format=xml
得到xml格式的如下结果:(代码中需要获取的城市和运营商黄色标注)
使用以下链接去浏览器中访问:
http://api.k780.com:88/app=phone.get&phone=18566669900
&appkey=14114&sign=ede788f7bf8d0678e281f660654ef995&format=json
得到json格式的如下结果:(代码中需要获取的城市和运营商黄色标注)
{"success":"1","result":{"status":"ALREADY_ATT","phone":"18566669900","area":"0755","postno":"518000","att":"中国,广东,深圳","ctype":"联通185卡","par":"1856666","prefix":"185","operators":"联通","style_simcall":"中国,广东,深圳","style_citynm":"中华人民共和国,广东省,深圳市"}}
查询效果图:
第一个按钮“查询”是使用HttpURLConnection+Thread+Handler+xml解析去获取;
第二个按钮“json查询”是使用HttpURLConnection+Thread+Handler+json解析去获取;
第三个按钮“使用Async-http-master xml查询”是使用AsyncHttpClient+AsyncHttpResponseHandler+xml解析去获取;
第四个按钮“使用Async-http-master json查询”是使用AsyncHttpClient+AsyncHttpResponseHandler+json解析去获取;
1 package com.example.day12_04phonenumberqurey; 2 3 import java.io.ByteArrayInputStream; 4 import java.io.InputStream; 5 import java.net.HttpURLConnection; 6 import java.net.URL; 7 8 import org.apache.http.Header; 9 import org.json.JSONException; 10 import org.json.JSONObject; 11 import org.xmlpull.v1.XmlPullParser; 12 13 import com.cskaoyan.webutils.WebUtils; 14 import com.loopj.android.http.AsyncHttpClient; 15 import com.loopj.android.http.AsyncHttpResponseHandler; 16 17 import android.app.Activity; 18 import android.os.Bundle; 19 import android.os.Handler; 20 import android.os.Message; 21 import android.util.Log; 22 import android.util.Xml; 23 import android.view.View; 24 import android.widget.EditText; 25 import android.widget.TextView; 26 import android.widget.Toast; 27 28 public class MainActivity extends Activity { 29 30 public static final String TAG = "phonenumberqurey"; 31 @Override 32 protected void onCreate(Bundle savedInstanceState) { 33 super.onCreate(savedInstanceState); 34 setContentView(R.layout.activity_main); 35 } 36 37 Handler hanlder = new Handler(){ 38 @Override 39 public void handleMessage(Message msg) { 40 super.handleMessage(msg); 41 switch (msg.what) { 42 case 1: 43 TextView tv_loaction = (TextView) findViewById(R.id.tv_location); 44 tv_loaction.setText((String)msg.obj); 45 break; 46 case 2: 47 Toast.makeText(MainActivity.this, (String)msg.obj, 0).show(); 48 break; 49 default: 50 break; 51 } 52 } 53 }; 54 55 public void query(View v){ 56 //先获取电话号码 57 EditText et_number = (EditText) findViewById(R.id.et_number); 58 String number = et_number.getText().toString(); 59 //http://api.k780.com:88...提供电话号码归属地查询的数据接口 60 final String path ="http://api.k780.com:88/?app=phone.get&phone=" 61 +number+"&appkey=14114&sign=ede788f7bf8d0678e281f660654ef995&format=xml"; 62 63 //发请求的线程 64 Thread thread = new Thread(){ 65 public void run() { 66 try { 67 URL url = new URL(path); 68 HttpURLConnection conn= (HttpURLConnection) url.openConnection(); 69 conn.setReadTimeout(5000); 70 conn.setConnectTimeout(5000); 71 conn.setRequestMethod("GET"); 72 conn.connect(); 73 74 String city =null; 75 String operator = null; 76 if(conn.getResponseCode()==200) 77 { 78 //登陆成功 79 //登陆失败? 80 InputStream is= conn.getInputStream(); 81 //String text = WebUtils.gettextFromInputStream(is, null); 82 XmlPullParser pullparser = Xml.newPullParser(); 83 pullparser.setInput(is, "UTF-8"); 84 85 //得到读取到的某部分的类型 86 int evenType = pullparser.getEventType(); 87 while(evenType!=XmlPullParser.END_DOCUMENT) 88 { 89 if (evenType==XmlPullParser.START_TAG) 90 { 91 Log.i(TAG, "START_TAG"+pullparser.getName()); 92 if ("operators".equals(pullparser.getName())) 93 { 94 operator=pullparser.nextText(); 95 } 96 if ("style_citynm".equals(pullparser.getName())) 97 { 98 city=pullparser.nextText(); 99 } 100 } 101 evenType=pullparser.next(); 102 } 103 104 Log.i(TAG,operator+":"+city); 105 Message msg = hanlder.obtainMessage(); 106 msg.what=1; 107 if(city==null||operator==null) 108 { 109 msg.obj="没有查询到结果"; 110 } 111 112 else 113 { 114 msg.obj= city+":"+operator; 115 } 116 hanlder.sendMessage(msg); 117 } 118 else 119 { 120 Message msg = hanlder.obtainMessage(); 121 msg.what=2; 122 msg.obj="没有链接到服务器"; 123 hanlder.sendMessage(msg); 124 } 125 126 } 127 catch (Exception e) 128 { 129 e.printStackTrace(); 130 } 131 }; 132 }; 133 thread.start(); 134 } 135 136 public void querybyjson(View v){ 137 //先获取电话号码 138 EditText et_number = (EditText) findViewById(R.id.et_number); 139 String number = et_number.getText().toString(); 140 final String path ="http://api.k780.com:88/?app=phone.get&phone="+ 141 number+"&appkey=14114&sign=ede788f7bf8d0678e281f660654ef995&format=json"; 142 143 144 //发请求的线程 145 Thread thread = new Thread() 146 { 147 public void run() 148 { 149 try 150 { 151 URL url = new URL(path); 152 HttpURLConnection conn= (HttpURLConnection) url.openConnection(); 153 conn.setReadTimeout(5000); 154 conn.setConnectTimeout(5000); 155 conn.setRequestMethod("GET"); 156 conn.connect(); 157 158 String city =null; 159 String operator = null; 160 if(conn.getResponseCode()==200) 161 { 162 //登陆成功 163 //登陆失败? 164 InputStream is= conn.getInputStream(); 165 String text = WebUtils.gettextFromInputStream(is, null); 166 167 JSONObject jsonObject = new JSONObject(text); 168 JSONObject result = jsonObject.getJSONObject("result"); 169 city= result.getString("style_citynm"); 170 operator = result.getString("operators"); 171 Log.i(TAG,operator+":"+city); 172 173 Message msg = hanlder.obtainMessage(); 174 msg.what=1; 175 176 if(city==null||operator==null) 177 msg.obj="没有查询到结果"; 178 else 179 msg.obj= city+":"+operator; 180 181 hanlder.sendMessage(msg); 182 } 183 else 184 { 185 Message msg = hanlder.obtainMessage(); 186 msg.what=2; 187 msg.obj="没有链接到服务器"; 188 hanlder.sendMessage(msg); 189 } 190 191 } 192 catch (Exception e) 193 { 194 e.printStackTrace(); 195 } 196 }; 197 }; 198 thread.start(); 199 } 200 201 public void querybyxml_async(View v) 202 { 203 EditText et_number = (EditText) findViewById(R.id.et_number); 204 String number = et_number.getText().toString(); 205 final String path ="http://api.k780.com:88/?app=phone.get&phone="+ 206 number+"&appkey=14114&sign=ede788f7bf8d0678e281f660654ef995&format=xml"; 207 208 AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); 209 asyncHttpClient.post(path, new Myhandler2()); 210 } 211 212 public void querybyjson_aysnc(View v) 213 { 214 EditText et_number = (EditText) findViewById(R.id.et_number); 215 String number = et_number.getText().toString(); 216 final String path ="http://api.k780.com:88/?app=phone.get&phone="+ 217 number+"&appkey=14114&sign=ede788f7bf8d0678e281f660654ef995&format=json"; 218 219 AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); 220 asyncHttpClient.post(path, new Myhandler()); 221 } 222 223 224 class Myhandler extends AsyncHttpResponseHandler 225 { 226 @Override 227 public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) 228 { 229 String city =null; 230 String operator = null; 231 232 JSONObject jsonObject =null; 233 try 234 { 235 jsonObject = new JSONObject(new String(responseBody)); 236 JSONObject result = jsonObject.getJSONObject("result"); 237 city= result.getString("style_citynm"); 238 operator = result.getString("operators"); 239 } 240 catch (JSONException e) 241 { 242 e.printStackTrace(); 243 } 244 TextView tv_loaction = (TextView) findViewById(R.id.tv_location); 245 tv_loaction.setText(city+":"+operator); 246 } 247 248 @Override 249 public void onFailure(int statusCode, Header[] headers, 250 byte[] responseBody, Throwable error) { 251 // TODO Auto-generated method stub 252 253 } 254 } 255 256 class Myhandler2 extends AsyncHttpResponseHandler 257 { 258 259 @Override 260 public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { 261 String city =null; 262 String operator = null; 263 264 XmlPullParser pullparser = Xml.newPullParser(); 265 ByteArrayInputStream bais= new ByteArrayInputStream(responseBody); 266 try { 267 pullparser.setInput(bais, "utf-8"); 268 //得到读取到的某部分的类型 269 int evenType = pullparser.getEventType(); 270 271 while(evenType!=XmlPullParser.END_DOCUMENT){ 272 if (evenType==XmlPullParser.START_TAG) { 273 Log.i(TAG, "START_TAG"+pullparser.getName()) ; 274 if ("operators".equals(pullparser.getName())) { 275 operator=pullparser.nextText(); 276 } 277 if ("style_citynm".equals(pullparser.getName())) { 278 city=pullparser.nextText(); 279 } 280 } 281 evenType=pullparser.next(); 282 } 283 } catch (Exception e) { 284 // TODO Auto-generated catch block 285 e.printStackTrace(); 286 } 287 TextView tv_loaction = (TextView) findViewById(R.id.tv_location); 288 tv_loaction.setText(city+":"+operator); 289 } 290 291 @Override 292 public void onFailure(int statusCode, Header[] headers, 293 byte[] responseBody, Throwable error) 294 { 295 // TODO Auto-generated method stub 296 297 } 298 } 299 }
1 package com.cskaoyan.webutils; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.InputStream; 5 6 public class WebUtils { 7 8 public static String gettextFromInputStream(InputStream is ,String charset){ 9 String text = null; 10 11 if(charset==null){ 12 charset="utf-8"; 13 } 14 15 try { 16 ByteArrayOutputStream baos= new ByteArrayOutputStream(); 17 18 byte[] b = new byte[1024]; 19 int len = 0; 20 while ((len=is.read(b))!=-1) { 21 baos.write(b, 0, len); 22 } 23 baos.close(); 24 25 text = new String(baos.toByteArray(), charset); 26 27 } catch (Exception e) { 28 // TODO Auto-generated catch block 29 e.printStackTrace(); 30 } 31 return text; 32 } 33 }
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" 6 android:paddingBottom="@dimen/activity_vertical_margin" 7 android:paddingLeft="@dimen/activity_horizontal_margin" 8 android:paddingRight="@dimen/activity_horizontal_margin" 9 android:paddingTop="@dimen/activity_vertical_margin" 10 tools:context="com.example.day12_04phonenumberqurey.MainActivity" > 11 12 <TextView 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:text="归属地查询" /> 16 17 <EditText 18 android:id="@+id/et_number" 19 android:layout_width="fill_parent" 20 android:layout_height="wrap_content" /> 21 22 <Button 23 android:layout_width="fill_parent" 24 android:layout_height="wrap_content" 25 android:onClick="querybyxml" 26 android:text="查询" /> 27 28 29 <Button 30 android:layout_width="fill_parent" 31 android:layout_height="wrap_content" 32 android:onClick="querybyjson" 33 android:text="json查询" /> 34 35 <Button 36 android:layout_width="fill_parent" 37 android:layout_height="wrap_content" 38 android:onClick="querybyxml_async" 39 android:text="使用Async-http-master xml查询" /> 40 41 <Button 42 android:layout_width="fill_parent" 43 android:layout_height="wrap_content" 44 android:onClick="querybyjson_aysnc" 45 android:text="使用Async-http-master json查询" /> 46 47 <TextView 48 android:id="@+id/tv_location" 49 android:layout_width="wrap_content" 50 android:layout_height="wrap_content" 51 android:text="归属地"/> 52 </LinearLayout>