• 关于开启线程与UI的操作


    当应用程序启动,创建了一个叫“main”的线程,用于管理UI相关,又叫UI线程。其他线程叫工作线程(Work Thread)。

    Single Thread Model(单线程模型)

    一个组件的创建并不会新建一个线程,他们的创建都在UI线程中进行,包括他们的回调方法,如onKeyDown()

    • 当在UI线程中进行某些耗时的操作时,将会阻塞UI线程,一般阻塞超过5秒就会报错

    UI线程是非线程安全的,所以,不能在工作线程中操作UI元素。

     

    两个原则

    • Do not block the UI thread (不要阻塞UI线程)
    • Do not access the Android UI toolkit from outside the UI thread (不要在工作线程中操作UI元素)

     

    在工作线程更新UI方法

    • Activity.runOnUiThread(new Runnable),在子线程中直接调用
      runOnUiThread(new Runnable() {
                                      @Override
                                      public void run() {
                                          mTvShow.setText(respone);
                                      }
                                  });
    • Handler,,在Main中新建Handle实例,重写handleMessage(),方法,在里面用接受值操作UI
      Handler handler = new Handler(){
              @Override
              public void handleMessage(Message msg) {
                 Bundle bundle = msg.getData();
                  String aa = bundle.getString("aa");
                  mTvShow.setText(aa);
              }
          };

      在子线程中赋值,并且传值给Handle。

      Bundle bundle = new Bundle();
      Message message = Message.obtain(); bundle.putString(
      "aa",responseData); message.setData(bundle); handler.sendMessage(message);
    • AsyncTask
      • execute()
      • doInBackground()
      • onPostExecute()
  • 相关阅读:
    Vscode 隐藏 工作区中的目录
    java 中 静态泛型方法书写
    Vscode 配置 maven debug
    vscode 配置 java utf-8 编码
    node.js 设置 淘宝 镜像
    vscode 注册表
    ESET Smart Security 6 – 免费60天(SG)
    WIN-8“内置管理员无法激活此应用”问题
    怎样更新PE内的工具
    使用Setup安装Windows8 RTM方法
  • 原文地址:https://www.cnblogs.com/zhoushenglei/p/7202506.html
Copyright © 2020-2023  润新知