1

我正在使用 OpenCV 库实现一个应用程序。处理完相机的inputFrame后,我想更新我的TextView。但是,我收到以下错误:

08-01 17:01:45.085: E/AndroidRuntime(16284): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

下面是我的应用程序的简化代码:

(...IMPORTS...)
public class ObjectTracker extends Activity implements CvCameraViewListener2, OnClickListener {

TextView resultTextView;

private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
    @Override
    public void onManagerConnected(int status) {
        switch (status) {
            case LoaderCallbackInterface.SUCCESS:
            {
                Log.i(TAG, "OpenCV loaded successfully");
                myJavaCameraView.enableView();
            } break;
            default:
            {
                super.onManagerConnected(status);
            } break;
        }
    }
};

public ObjectTracker() {
    Log.i(TAG, "Instantiated new " + this.getClass());
}

@Override
public void onCreate(Bundle savedInstanceState) {
    (...)
    resultTextView = (TextView)           
    findViewById(R.id.activity_object_tracker_native_textview_result);
}

@Override
public void onPause()
{
    super.onPause();
    if (myJavaCameraView != null)
        myJavaCameraView.disableView();
}

@Override
public void onResume()
{
    super.onResume();
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
}

public void onDestroy() {
    super.onDestroy();
    if (myJavaCameraView != null)
        myJavaCameraView.disableView();
}

public void onCameraViewStarted(int width, int height) {
}

public void onCameraViewStopped() {
}

public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    (...)
    return trackFilteredObject(filteredFrame, newInputFrame);
}

public Mat trackFilteredObject(Mat filteredFrame, Mat inputFrame)
{
    (...)

    //HERE I WANT TO UPDATE MY TEXT VIEW

    return inputImage;
}

}

我不知道我应该把更新代码放在哪里来摆脱这个错误。有人能帮我吗?

4

2 回答 2

4

UI 的东西只能从主 UI 线程修改。你trackFilteredObject的回调方法(你更新你的地方TextView)显然是从后台线程调用的。

要解决此问题,您可以使用Activity#runOnUiThread方法,该方法可让您发布可在 UI 线程上执行的可运行对象。

尝试更换

//HERE I WANT TO UPDATE MY TEXT VIEW

经过

runOnUiThread(new Runnable() {

    public void run() {
        //HERE I WANT TO UPDATE MY TEXT VIEW
    }
});
于 2013-08-01T09:11:33.103 回答
0

我找到了一个解决方案:

public Mat trackFilteredObject(Mat filteredFrame, Mat inputFrame)
{
    (...)

    runOnUiThread(new Runnable() {

        public void run() {
            //HERE I UPDATE TEXT VIEW
        }
    });

    return inputImage;
}

感谢@fiddler的帮助

于 2013-08-02T05:10:30.587 回答