Skip to content

Latest commit

 

History

History
153 lines (122 loc) · 3.64 KB

线程.md

File metadata and controls

153 lines (122 loc) · 3.64 KB

线程

不应在子线程中操作 UI

在 UI 线程延时的用法

postDelayed

new Handler().postDelayed(new Runnable(){ 
    public void run(){ 
        // 运行在ui线程
        System.out.println(1);
    } 
}, 2000);

Thread

new Thread (new Runnable(){ 
    public void run(){ 
        Thread.sleep(2000); 
        // 运行在子线程
        System.out.println(1);
    } 
}).start();

TimerTask

TimerTask task = new TimerTask(){ 
    public void run(){ 
        // TODO
    } 
} 
Timer timer = new Timer(); 
timer.schedule(task, 2000);

android延时执行的几种方式_fuyinghaha的专栏-CSDN博客_android 延时

子线程更新 UI

runOnUiThread

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();

Thread中runOnUiThread的简单使用_cf8833的博客-CSDN博客_runonuithread

handler

声明handler
private MainHandler mainHandler;
// 消息类型标志位
private static final int MSG_APP_UPDATE_SUCCESS = 10;
private static final int MSG_APP_UPDATE_FAILED = 11;
handler定义
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();
        }
    }
}
初始化 handler
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);
        }
    }
});