1

I am trying to update my UI from the GLThread with a handler. I have read that everything in "handleMessage" will be performed in the UI Thread but I still get this exception:

05-31 09:22:55.653: E/AndroidRuntime(26273): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Here is my handler:

public class VideoPlayerCallback implements Handler.Callback {

        public static final int PLAY = 0;
        public static final int STOP = 1;
        public boolean handleMessage(Message msg) {
            if(msg.what == VideoPlayerCallback.PLAY) {
                ARVideoTemplate videoTemp = (ARVideoTemplate) msg.obj; 
                String uriPath = "android.resource://" + getPackageName() +"/raw/"+videoTemp.getFileName();
                updateVideo(uriPath); // UI Actions
                return true;        
            }
            else if(msg.what == VideoPlayerCallback.STOP){
                updateVideo(null); // UI Actions
                return true;
            }
            return false;    
        }       
    }

Then something like this to put this handler to my GLRenderer:

Handler player = new Handler(new VideoPlayerCallback());
((ARGLSurfaceView) mGLSurfaceView).setVideoView(player);

And the call from GLRenderer:

Message msg = Message.obtain(mVideoPlayer);
msg.obj = video;
msg.what = VideoPlayerCallback.PLAY;
this.mVideoPlayer.dispatchMessage(msg);

What should I change to access the ui thread properly? Thank you in advance!

4

2 回答 2

0

I don't know about that callback-subclassing you are doing, but a handler should work fine, just two things to do:

  • You create the handler on the thread that it should post code to.

  • You use the handler.post()-method to post he source to the UI thread, like this:

handler.post(new Runnable() {
    @Override
    public void run() {
        drawStuffToScreen();
    }
});
于 2013-05-31T10:44:09.057 回答
0

I have found my fault. I have to call

this.mVideoPlayer.sendMessage(msg);

instead of dispatchMessage(msg). Then my handler runs on the UI thread.

于 2013-06-10T13:46:02.390 回答