android Activity runOnUiThread() 方法使用

本文介绍了一种在Android中更新UI的新方法:使用Activity的runOnUiThread(Runnable)方法。这种方法相较于传统的Handler方式更为简洁。通过示例代码展示了如何在一个非UI线程中延迟执行任务,并在UI线程中更新界面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

 

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

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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 * 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();
    }
}

转自https://www.cnblogs.com/zhaoyanjun/archive/2016/05/11/5483221.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值