android Activity runOnUiThread() 方法的使用

本文介绍了如何使用Activity.runOnUiThread(Runnable)方法更新UI,并通过示例展示了如何利用ProgressDialog显示加载提示。此外,还讨论了非UI线程下更新UI的具体实现。

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

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

Runnable对像就能在ui程序中被调用。

/**

 * 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();

    }

}

从上面的源代码中可以看出,程序首先会判断当前线程是否是UI线程,如果是就直接运行,如果不是则post,这时其实质还是使用的Handler机制来处理线程与UI通讯。

 

        private ProgressDialog progressDialog;
 Context mContext;


progressDialog = new ProgressDialog(mContext); String stri = mContext.getResources().getString(R.string.Is_sending_a_request); progressDialog.setMessage(stri); progressDialog.setCanceledOnTouchOutside(false); progressDialog.show(); new Thread(new Runnable() { public void run() { try { ((Activity)mContext).runOnUiThread(new Runnable() { public void run() { progressDialog.dismiss(); String s1 = mContext.getResources().getString(R.string.send_successful); Toast.makeText(mContext, s1, Toast.LENGTH_LONG).show(); } }); } catch (final Exception e) { ((Activity)mContext).runOnUiThread(new Runnable() { public void run() { progressDialog.dismiss(); String s2 = mContext.getResources().getString(R.string.Request_add_buddy_failure); Toast.makeText(mContext, s2 + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } }).start();

用这种方式创建ProgressDialog就比较方便,或者刷新adapter也比使用Thread+Handler方便。

如果不是在activity中创建,需要在前面加上((Activity)mContext).

 

转载于:https://www.cnblogs.com/tangZH/p/6107556.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值