星空网 > 软件开发 > 操作系统

android Activity runOnUiThread() 方法使用

android 中我们一般用 Handler 做主线程 和 子线程 之间的通信 。

现在有了一种更为简洁的写法,就是 Activity 里面的 runOnUiThread( Runnable )方法。

 

利用Activity.runOnUiThread(Runnable)把更新ui的代码创建在Runnable中,然后在需要更新ui时,把这个Runnable对象传给Activity.runOnUiThread(Runnable)。 

Runnable对像就能在ui程序中被调用。如果当前线程是UI线程,那么行动是立即执行。如果当前线程不是UI线程,操作是发布到事件队列的UI线程。

 

package com.app;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.widget.Toast;public class MainActivity extends AppCompatActivity {  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    //创建一个线程    new Thread(new Runnable() {      @Override      public void run() {        //延迟两秒        try {          Thread.sleep( 2000 );        } catch (InterruptedException e) {          e.printStackTrace();        }        runOnUiThread(new Runnable() {          @Override          public void run() {            Toast.makeText(MainActivity.this, "hah", Toast.LENGTH_SHORT).show();          }        });      }    }).start();  }}

  

 Activity的runOnUiThread(Runnable)

  /**   * Runs the specified action on the UI thread. If the current thread is the UI   * thread, then the action is executed immediately. If the current thread is   * not the UI thread, the action is posted to the event queue of the UI thread.   *   * @param action the action to run on the UI thread   */  public final void runOnUiThread(Runnable action) {    if (Thread.currentThread() != mUiThread) {      mHandler.post(action);    } else {      action.run();    }  }

  

 




原标题:android Activity runOnUiThread() 方法使用

关键词:Android

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

海外跨境物流:https://www.goluckyvip.com/tag/93066.html
跨境海外物流:https://www.goluckyvip.com/tag/93067.html
跨境电商物流的优势:https://www.goluckyvip.com/tag/93068.html
冷链跨境物流:https://www.goluckyvip.com/tag/93069.html
应对运费上涨:https://www.goluckyvip.com/tag/9307.html
国外的跨境物流:https://www.goluckyvip.com/tag/93070.html
月活用户超20亿!万亿市值巨头对中国商家进一步开闸放流 :https://www.kjdsnews.com/a/1836412.html
九寨沟周围必去的景点推荐:https://www.vstour.cn/a/363190.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流