如果可能,我们需要使用runOnUiThread在Android应用程序? [英] When may we need to use runOnUiThread in android application?

查看:132
本文介绍了如果可能,我们需要使用runOnUiThread在Android应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用这个功能来运行一个线程 runOnUiThread A code样本。为何以及何时可能需要使用它?

修改

要使用什么的AsyncTask 类,什么优点缺点 ??

解决方案

您必须使用 runOnUiThread()当你想更新来自非UI线程的UI 。对于EG-如果您想更新从后台线程的用户界面。您也可以使用处理程序同样的事情。

从文件 -

  

运行在UI线程上指定的操作。如果当前线程是   UI线程,则该动作被立即执行。如果当前   线程不是UI线程,该动作被发布到事件队列   UI线程的。

语法 -

  Activity_Name.this.runOnUiThread(新的Runnable(){

            @覆盖
            公共无效的run(){
                //你的东西更新UI

            }
        });
 

更新 -

  AsycnTask  - 
 

  

如果你想要做一些网​​络运行或任何块   在这种情况下的AsyncTask你的用户界面是最好的选择。有几个   其他方法执行相同的后台操作,你可以   使用服务 IntentService 也做后台操作。   使用的AsyncTask将帮助你做你的用户界面的工作,也不会阻止   你的用户界面,直到你的后台操作是怎么回事。

从文件 -

  

的AsyncTask能够适当且易于使用的用户界面线程。这个类   允许在UI上进行后台操作并公布结果   螺纹,而不必操纵线程和/或处理程序。

I have a code sample that uses this function to run a thread runOnUiThread. why and when may we need to use it?

edit

What about to use AsyncTask class, what's the pros and cons??

解决方案

You have to use runOnUiThread() when you want to update your UI from a Non-UI Thread. For eg- If you want to update your UI from a background Thread. You can also use Handler for the same thing.

From the Docs -

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.

Syntax -

       Activity_Name.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // your stuff to update the UI

            }
        });

Update -

AsycnTask -

If you want to do some Network operation or anything that blocks your UI in that case AsyncTask is best options. There are several other ways for performing the same Background Operations as you can use Service, IntentService also for doing Background Operations. Using AsyncTask will help you doing your UI work and also won't block your UI until your background Operation is going on.

From the Docs -

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

这篇关于如果可能,我们需要使用runOnUiThread在Android应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆