android Activity runOnUiThread() 方法的使用
转载请标明出处:https:////www.cnblogs.com/tangZH/p/6107556.html
更多精彩文章: http://77blogs.com/?p=138
利用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). 。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?