Android的Activity.runOnUiThread也不是一成不变的,所以我如何使用它? [英] Android's Activity.runOnUiThread is not static, so how can i use it?

查看:431
本文介绍了Android的Activity.runOnUiThread也不是一成不变的,所以我如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个线程执行昂贵的东西,并从该线程我想火runOnUiThread在主(活动)类。很显然,我不能让我的活动类(主要)的一个实例。所以,如果我尝试

For example, if I have a thread doing expensive stuff, and from that thread I want to fire runOnUiThread in the Main (activity) class. Obviously I shouldn't make an instance of my activity class (Main). So if I try

 Main.runOnUiThread(mRunnable);

这是我的线程它给了我一个错误说这不是一个静态方法,并为此而不能在我的方式进行访问。现在,我的理解是,该活动类几乎几乎静态的方式进行访问。
我将如何做到这一点?

from my thread it gives me an error saying it's not a static method, and therefor it can't be accessed in my way. Now my understanding would be that the activity class is nearly almost accessed in a static way.
How would I do this?

(顺便说一句:我这样做,因为我得到的 CalledFromWrongThreadException,只有原始的创建一个视图层次可以触摸它的观点线程的)

(Btw: I'm doing this because I was getting CalledFromWrongThreadException, Only the original thread that created a view hierarchy can touch it's views)

推荐答案

Raunak有正确的想法。我就补充一点,你也可以指定方法sendEmptyMessage整数作为标识符的处理程序。这将允许您创建一个处理程序,可以处理所有的用户界面的更新,如:

Raunak has the right idea. I'll just add that you can also specify an integer in the method sendEmptyMessage as an identifier to the handler. This will allow you to create one handler that can handle all of your UI updates, e.g.

public static final int EXAMPLE = 0;
public static final int ANOTHER_EXAMPLE = 1;

private final Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        switch( msg.what ){
            case EXAMPLE: 
                //Perform action
                break;
            case ANOTHER_EXAMPLE;
                //Perform action
                break;
        }
    }
} 

//Call to submit handler requesting the first action be called
handler.sendEmptyMessage(EXAMPLE);

希望这有助于!

Hope this helps!

这篇关于Android的Activity.runOnUiThread也不是一成不变的,所以我如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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