Android的Java的runOnUiThread() [英] Android Java runOnUiThread()

查看:485
本文介绍了Android的Java的runOnUiThread()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在瞎搞了一下与runOnUiThread方法。如果我只是做了一种方法,我的活动:

I have been messing around a bit with the runOnUiThread method. And if I simply make a method in my activity:

public void Test()
{
    runOnUiThread(new Runnable() 
    {
        public void run() 
        {
            Log.v("mainActivity", "test");
        }
    });     
}

我注意到,这可运行只运行一次。然而,这是没有问题的。我想知道的是,如果我已经完全错过了一些东西,并做一些事情的背景,将导致帧率下降时,我已执行方法几次。

I noticed that this runnable only runs once. However, this is not a problem. What I was wondering is if I have completely missed something and it does something in the background that would cause a frame rate drop when I have executed the method a couple times.

推荐答案

这是完整的身体<一个href="http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29">Activity.runOnUiThread(Runnable):

public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}

该方法的主体仍然是在后台线程中执行,并mHandler类 android.os.Handler的实现了的Runnable内部队列贴吧,所以,除非你正在做的工作,堵在了Runnable(这是一个没有没有对UI线程)或调用此方法向上在短短一千倍,你应该不会看到任何区别。

The method body is still executed in your background thread, and mHandler of class android.os.Handler implements an internal queue for Runnables posted to it, so unless you're doing blocking work in the Runnable (which is a big no-no on the UI Thread) or calling this method upwards of a thousand times in a short period, you should not see any difference.

现在,如果你调用<一href="http://developer.android.com/reference/android/os/Handler.html#postAtFrontOfQueue%28java.lang.Runnable%29">Handler.postAtFrontOfQueue(Runnable),那么会是一个问题,因为你的Runnable基本上是插队。在这种情况下,这可能会导致口吃,因为你的Runnable正在执行,而不是一个需要发生(如滚动)任何用户界面的更新。

Now, if you were calling Handler.postAtFrontOfQueue(Runnable), then there'd be an issue, because your Runnable is essentially "cutting in line". In this case, that would likely cause a stutter, because your Runnable is being executed instead of any UI updates that needed to take place (like scrolling).

请注意,您只的需要的到UI线程上运行用户界面的更新,比如调用任何方法在View(因而命名为UI线程,以及为什么这种方法存在)或任何操作,其中的文件明确规定,它需要在UI线程上运行。否则,如果你已经在后台线程,有没有真正的理由离开了。

Note that you only need to run UI updates on the UI thread, like calling any methods on a View (thus the name "UI Thread" and why this method exists) or any operation where the documentation explicitly states that it needs to be run on the UI thread. Otherwise, if you're already on a background thread, there's no real reason to leave it.

这篇关于Android的Java的runOnUiThread()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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