不应在子线程中操作 UI
new Handler().postDelayed(new Runnable(){
public void run(){
// 运行在ui线程
System.out.println(1);
}
}, 2000);
new Thread (new Runnable(){
public void run(){
Thread.sleep(2000);
// 运行在子线程
System.out.println(1);
}
}).start();
TimerTask task = new TimerTask(){
public void run(){
// TODO
}
}
Timer timer = new Timer();
timer.schedule(task, 2000);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
@Override
public void run() {
// 运行在ui线程
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
private MainHandler mainHandler;
// 消息类型标志位
private static final int MSG_APP_UPDATE_SUCCESS = 10;
private static final int MSG_APP_UPDATE_FAILED = 11;
class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
if (msg.what == MSG_APP_UPDATE_SUCCESS) {
JsonResult json = (JsonResult) msg.obj;
if (json.getData().get("isNeedUpdate").equals(1)) {
loadingAlert.dismiss();
String url = json.getData().getString("url");
String version = json.getData().getString("versionName");
String updateMsg = json.getData().getString("msg");
startUpdate(url, version, updateMsg);
}
} else if (msg.what == MSG_APP_UPDATE_FAILED) {
loadingAlert.dismiss();
Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
}
}
}
mainHandler = new MainHandler();
可利用Message
对象传值:
what
: int,一般用于传递标志位
obj
: Object,一般用于传递对象、值
arg1
: int
arg2
: int
OkHttpClient client = new OkHttpClient();
FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
formBody.add("version", String.valueOf(packageCode(this)));//传递键值对参数
Request request = new Request.Builder()
.url(ServerConfig.URL_API + "/checkUpdate")
.post(formBody.build())
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message msg = new Message();
msg.what = MSG_APP_UPDATE_FAILED;
mainHandler.sendMessage(msg);
Log.d("noa", "checkUpdate Failed");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
JsonResult jsonResult = JsonResult.parse(response.body().string());
Message msg = new Message();
msg.what = MSG_APP_UPDATE_SUCCESS;
msg.obj = jsonResult;
mainHandler.sendMessage(msg);
}
}
});