总结Android中多线程更新应用的页面信息的方式

2019-12-10 18:58:19于海丽
易采站长站为您分析总结Android中多线程更新应用的页面信息的方式,文中共总结了runOnUiThread、Handler、AsyncTask异步以及View直接在UI线程中更新的方法,需要的朋友可以参考下  

一、runOnUiThread的用法
runOnUiThread是Activity的内部方法,使用时最好指定当前的环境变量(Context)。

new Thread(new Runnable() {

    @Override
    public void run() {
      runOnUiThread(new Runnable() {
        public void run() {
          Toast.makeText(mainActivity.this,"UI操作。。。",0).show();
        }
      });

    }
  }).start();

执行runOnUiThread这个方法会调用父类中的

public final void runOnUiThread(Runnable action){
 if(Thread.currentThread()!=mUiThread){
 mHandler.post(action);
 }else{
  action.run();
 }
}

二、新线程中View直接在UI线程中更新的方法

textView.postDelayed(new Runnable() {

    @Override
    public void run() {
      textView.setText("Test View.post(Runnable)");

    }
  }, 1000);
-

 textView.post(new Runnable() {

    @Override
    public void run() {
      textView.setText("Test View.postDelay(Runnable,long)");

    }
  });

三、Handler(消息传递机制)使用

Handler myHandler = new Handler(){
 public void handleMessage(Message msg){
  super.handleMessage(msg); 
  }
};