在UI线程中定义并使用handler消息机制可以有效的帮助与其他线程的通信
private Handler mHandler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case SUCCESS_NUMBER:{ //通过getData函数得到通过消息机制获取到的数据 Bundle bundle=msg.getData(); versionName=bundle.getString("versionName"); versionCode=bundle.getString("versionCode"); versionDes=bundle.getString("versionDes"); updatePath=bundle.getString("updatePath"); //建议得到的数据仅限于handleMessage这个函数中使用,因为线程执行顺序无法预测 checkVersion(); }break; } } };
new Thread(){ @Override public void run() { String path="http://10.25.13.155/update/updateInfo.json"; try { URL url=new URL(path); HttpURLConnection connection= (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); if(connection.getResponseCode()==200){ InputStream is=connection.getInputStream(); String info= StreamUtil.getInfo(is); if(info!=null){ Message message= Message.obtain(); //Bundle 相当于Map,用来存储键值对 Bundle bundle=new Bundle(); JSONObject jsonObject=new JSONObject(info); versionName = jsonObject.getString("versionName"); versionCode = jsonObject.getString("versionCode"); versionDes = jsonObject.getString("versionDes"); updatePath = jsonObject.getString("updatePath"); bundle.putString("versionName",versionName); bundle.putString("versionCode",versionCode); bundle.putString("versionDes",versionDes); bundle.putString("updatePath",updatePath); message.setData(bundle); message.what=SUCCESS_NUMBER; //延时跳转 long endTime=SystemClock.currentThreadTimeMillis(); if((endTime-startTime)<5000){ SystemClock.sleep(5000-(endTime-startTime)); } //将信息通过消息机制传送到UI线程 mHandler.sendMessage(message); }else{ Log.i("联网失败","未获得信息"); } }else{ Log.i("联网信息","未取得链接"); } } catch (Exception e) { e.printStackTrace(); } } }.start();
private void checkVersion(){ if(mLocalVersionCode<Integer.parseInt(versionCode)){ Log.i("比较成功是否更新","是"+versionCode); }else { Intent intent=new Intent(this,IndexActivity.class); startActivity(intent); finish(); } }