android Activity runOnUiThread() 方法使用

简介: 在android 中我们一般用 Handler 做主线程 和 子线程 之间的通信 。 现在有了一种更为简洁的写法,就是 Activity 里面的 runOnUiThread( Runnable )方法。
在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();
        }
    }

  

 

相关文章
|
4天前
|
Android开发
Android调用相机与相册的方法1
Android调用相机与相册的方法
39 0
|
4天前
|
XML Java Android开发
利用Bundle实现Android Activity间消息的传递
利用Bundle实现Android Activity间消息的传递
12 2
|
4天前
|
机器学习/深度学习 Java Shell
[RK3568][Android12.0]--- 系统自带预置第三方APK方法
[RK3568][Android12.0]--- 系统自带预置第三方APK方法
45 0
|
3天前
|
Android开发
Android获取蓝牙设备列表的方法
Android获取蓝牙设备列表的方法
14 5
|
3天前
|
Android开发
Android获取当前系统日期和时间的三种方法
Android获取当前系统日期和时间的三种方法
16 4
|
4天前
|
API 开发工具 Android开发
调用Android原生@SystemApi、@Hide方法
调用Android原生@SystemApi、@Hide方法
8 1
|
4天前
|
Android开发 数据库管理
Android如何在Activity和Service之间传递数据
Android如何在Activity和Service之间传递数据
12 3
|
4天前
|
程序员 Android开发
Android亮度调节的几种实现方法
Android亮度调节的几种实现方法
11 0
|
4天前
|
Shell Android开发
Android Activity重写dump方法实现通过adb调试代码
Android Activity重写dump方法实现通过adb调试代码
17 0
|
4天前
|
Android开发
Android APP 隐藏系统软键盘的方法
Android APP 隐藏系统软键盘的方法
33 0