Android中Handler消息传递机制

因为是在项目中的收获,所以不全,以后遇到其他的我会加上。

安卓中用Handler机制来实现主线程和子线程之间的通信,通信的媒介是Message的实例。

首先要在主线程声明一个Handler对象,然后重写里面的handMessage(Message msg)方法,用switch-case语句进行匹配处理


在子线程中,new一个Message实例msg,可以填写msg.what和msg.object,类似一个map对象,用主线程中的handler的handleMessage(msg)handler的handleMessage(msg)



private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case ENTER_HOME:
				Toast.makeText(getApplicationContext(), "进入界面", 0).show();
				break;
			case UPDATE:
				Toast.makeText(getApplicationContext(), "更新", 0).show();
				break;
			case NET_ERROR:
				Toast.makeText(getApplicationContext(), "网络未连接", 0).show();
				break;
			case READ_ERROR:
				Toast.makeText(getApplicationContext(), "流读取失败", 0).show();
				break;	
			case JSON_ERROR:
				Toast.makeText(getApplicationContext(), "json读取失败", 0).show();
				break;
			}
		}
		
	};
<span style="font-family: Arial, Helvetica, sans-serif;">private void checkUpdate() {</span>
		// TODO Auto-generated method stub
		new Thread(){
			public void run() {
				Message msg = new Message();
				long startTime = System.currentTimeMillis();
				try {
					URL url = new URL("..");
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.setRequestMethod("GET");
					conn.setReadTimeout(5000);
					int code = conn.getResponseCode();
					if(code==200) {
						InputStream is = conn.getInputStream();
						String json = StreamTools.readFromStream(is);
						JSONObject obj = new JSONObject(json);
						verson = obj.getString("verson");
						description = obj.getString("description");
						apkUrl = obj.getString("apkUrl");
						if(getVerson().equals(verson)) {
							//进入主界面
							msg.what = ENTER_HOME;
						} else {
							//更新
							msg.what = UPDATE;
						}
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					msg.what = NET_ERROR;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					msg.what = READ_ERROR;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					msg.what = JSON_ERROR;
				}finally{
					long endTime = System.currentTimeMillis();
					long dTime = startTime - endTime;
					if(dTime < 2000) {
						try {
							Thread.sleep(2000 - dTime);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					handler.sendMessage(msg);
				}
			};
			
		}.start();
	}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值