android随笔01——handler

handler : 当需要在子线程更新UI的时候,可以用handler来完成;

步骤:

1.在主线程中新建一个handler对象:

(以软件联网检查更新的部分代码来演示)

private String desc;

private String updateurl;

private final int GO_HOME = 100;

private final int SHOW_UPDATE_DIALOG = 101;

private Handler handler = new Handler() { //主线程中创建handler对象

public void handleMessage(android.os.Message msg) { //带参的handleMessage方法接收传递过来的Mseeage

switch (msg.what) {

case GO_HOME:

Intent intent = new Intent(SplashActivity.this,MainActivity.class);

startActivity(intent); //若打开了新页面后 不想再让页面退回到当前的闪溅页面 那么在这里加一个finish结束掉当前页面即可

finish();

break;

case SHOW_UPDATE_DIALOG:

showUpdateDialog();

break; } }

};

private void chenckupdate() {

// 联网必须在子线程进行

new Thread() { // 匿名内部类开启子线程

public void run() {

Message msg = Message.obtain(); // 创建信息对象 obtain() 检查缓存中是否有数据 有就调用缓存中的 ,没有就新建一个message对象

try {

// 通过HttpURLConnection获得网络连接 ​

URL url = new URL("http://192.168.1.151:8080/sjws_361/update.json");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");// 设置请求方式

// 学习中一般设置为2000以节省时间,工作中一般设置为30秒 conn.setConnectTimeout(2000); // 设置联网超时时间

conn.setReadTimeout(2000); // 设置读取超时时间

// 获得响应码

int code = conn.getResponseCode();

// 对联网结果进行判断

if (code == 200) { // 联网成功

InputStream is = conn.getInputStream();// 获得联网,返回的输入流

// 将返回的输入流转换成一个字符串

String jsonStr = StreamUtils.convertStream2str(is);

// jsonStr = new String(jsonStr.getBytes(),"utf-8"); //测试

// System.out.println(jsonStr);

// 创建一个JSONObject对象以获取JSON的具体内容

JSONObject jobj = new JSONObject(jsonStr);

int serverCode = jobj.getInt("code");

desc = jobj.getString("desc");

updateurl = jobj.getString("url");

if (code == serverCode) { //网络版本与当前版本一致

msg.what = GO_HOME; //无需更新 直接进入主页面

} else { //版本不一致

msg.what = SHOW_UPDATE_DIALOG; //调用系统安装页面

}

} else { // 联网失败

MyUtils.showToast(SplashActivity.this, "联网失败" + code); // 为了让软件具有更好地客户体验 将联网失败的作物提示信息进行优化 "联网失败 错误码:4001"

msg.what = GO_HOME; //设置返回信息通过handler判断信息以执行跳转回主页面的动作

}

}

catch (MalformedURLException e) {

e.printStackTrace();

MyUtils.showToast(SplashActivity.this, e.getMessage()); // 客户体验优化 将e.getMessage()改为 "联网失败 错误码:4002"

msg.what = GO_HOME;

} catch (IOException e) {

e.printStackTrace();

MyUtils.showToast(SplashActivity.this, e.getMessage()); // 客户体验优化 将e.getMessage()改为 "联网失败 错误码:4002"

msg.what = GO_HOME;

} catch (JSONException e) {

e.printStackTrace();

MyUtils.showToast(SplashActivity.this, e.getMessage()); // 客户体验优化 将e.getMessage()改为 "联网失败 错误码:4002"

msg.what = GO_HOME;

} finally { // 为了确保message绝对能被发送出去所以就用finally // 通过handler将收集到的message发送出去

handler.sendMessage(msg); //调用handler方法 将收集到的message传递到handler中进行判断

long now = SystemClock.uptimeMillis();

if (now - startTime < 2000) { // 联网速度太快 闪屏页面效果受到了影响 // 再睡一会

try { // 凑够2000毫秒的时间

Thread.sleep((startTime) + 2000 - now);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

};

}.start(); }

​​​

你可能感兴趣的:(android随笔01——handler)