因为是在项目中的收获,所以不全,以后遇到其他的我会加上。
安卓中用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();
}