TimerTask并在UI线程上设置视图

时间:2016-02-25 03:08:30

标签: java android multithreading runnable timertask

我正在尝试使用TimerTask检测用户长按。代码是在用户按住按钮的时间超过LONG_PRESS_TIMEOUT变量时应该执行的runnable。短按事件有效,但是当执行下面的代码时,调用TimerTask时,我收到错误Only the original thread that created a view hierarchy can touch its views.

 View.OnTouchListener detectClickAndHoldListener = new View.OnTouchListener() {

        private Timer timer = new Timer();
        private long LONG_PRESS_TIMEOUT = 1337; // TODO: your timeout here
        private boolean wasLong = false;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Log.d(getClass().getName(), "touch event: " + event.toString());

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                // touch & hold started
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        wasLong = true;
                        snap.setBackgroundResource(R.drawable.cam_rec);
                        try {
                            initRecorder(mCameraView.getHolder().getSurface());
                            mMediaRecorder.start();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        // touch & hold was long
                    }
                }, LONG_PRESS_TIMEOUT);
                return true;
            }

            if (event.getAction() == MotionEvent.ACTION_UP) {
                // touch & hold stopped
                timer.cancel();
                if(!wasLong){
                    mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
                    snap.setBackgroundResource(R.drawable.filled_cam);
                }
                else {
                    mMediaRecorder.stop();
                    mMediaRecorder.reset();
                }
                timer = new Timer();
                return true;
            }

            return false;
        }
    };

1 个答案:

答案 0 :(得分:1)

YourActivity.this.runOnUiThread(new Runnable(){
@Override
public void run(){
    try {
             initRecorder(mCameraView.getHolder().getSurface());
             mMediaRecorder.start();
    } catch (IOException e) {
         e.printStackTrace();
    }
}
);