【问题标题】:Accessing Activity from Thread Using Listener使用监听器从线程访问活动
【发布时间】:2012-09-26 18:57:37
【问题描述】:

我有两个类:一个控制多个小部件的活动类,然后是一个实现线程的自定义 SurfaceView 类。 (很常见)。我在 SurfaceView 类中实现了一个简单的自定义侦听器,每当我想在 Activity 类的各种小部件中更新的线程中的某些值发生变化时,我都可以触发该侦听器。

public class MyActivity extends Activity{

    CustomView myThreadView = (CustomView)findViewById(...);

    myThreadView.setListener(new OnStatChangeListener(){
        public void onChange(int change){
            //Change various widgets based on value fed in.
        }
    });

    // All of the other things (View setups, listeners, onCreate, etc.)
}

线程类:

public class CustomView extends SurfaceView implements Runnable(){
    //.. The usual thread and View stuff.

    public sListener;

    public interface OnStatChangeListener {
        public onChange(int change);
    }

    public void setListener(OnStatChangeListener oscl){
        sListener = oscl;
    }

    public void externalAccessMethod(){
        // Some thing changes a stat that is reflected in the Activity's widgets.
        sListener.onChange(value);
    }

    public void methodRunByThread(){
        // Something else changes that I want to update.
        sListener.onChange(value);
    }

    // Everything else (not relevant).
}

每当我从 Activity 的类调用的方法中调用 onChange 时,它​​都可以正常工作。但是,每当线程本身更新它的状态(在我的例子中是一个重绘方法)并且我调用 onChange 方法时,我都会得到一个 CalledFromWrongThread 异常。有人可以解释为什么一个有效但另一个无效,以及从单独的线程实际实现小部件更新的最佳实践是什么? Activity 中的单独处理程序线程似乎没有必要,因为无论如何我都知道何时更新值。

【问题讨论】:

    标签: android android-view android-handler


    【解决方案1】:

    因为您只能从 UI 线程访问视图。每个应用程序有一个 UI 线程。现在您从另一个不正确的线程访问视图并导致异常。

    您可以这样做:

    在你的 Activity 的 onChange 中,将所有内容包装在 runOnUiThread 中

    或更好:

    使用处理程序而不是您自己的听众(需要一些学习但需要付费)

    【讨论】:

    • 我想我明白这一点,但是如果需要它在一个可以在活动中运行的方法中,那么制作自定义侦听器有什么意义呢?
    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 2016-02-25
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多