码迷,mamicode.com
首页 > 其他好文 > 详细

hander同步技巧 利用post之后的消息是最后完成的,实现同步。关键看waitDone的实现。带面精简Camera应用。

时间:2015-04-29 15:04:55      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:handle同步技巧

    private void testWait(){
		HandlerThread ht = new HandlerThread("Camera Handler Thread");
        ht.start();
        mCameraHandler = new CameraHandler(ht.getLooper());
        mCameraHandler.obtainMessage(OPEN_CAMERA, 1, 0).sendToTarget();
        boolean ret = false;
        ret = mCameraHandler.waitDone();
        Log.v(TAG, "ret = " + ret);
    }
    
    private class CameraHandler extends Handler {
        CameraHandler(Looper looper) {
            super(looper);
        }

        /**
         * Waits for all the {@code Message} and {@code Runnable} currently in the queue
         * are processed.
         *
         * @return {@code false} if the wait was interrupted, {@code true} otherwise.
         */
        public boolean waitDone() {
            final Object waitDoneLock = new Object();
            final Runnable unlockRunnable = new Runnable() {
                @Override
                public void run() {
                    synchronized (waitDoneLock) {
                    	Log.v(TAG, " notifyAll start");
                        waitDoneLock.notifyAll();
                    }
                }
            };

            synchronized (waitDoneLock) {
                mCameraHandler.post(unlockRunnable);
                try {
                	Log.v(TAG, "start wait");
                    waitDoneLock.wait();
                } catch (InterruptedException ex) {
                    Log.v(TAG, "waitDone interrupted");
                    return false;
                }
            }
            return true;
        }

        /**
         * This method does not deal with the API level check.  Everyone should
         * check first for supported operations before sending message to this handler.
         */
        @Override
        public void handleMessage(final Message msg) {
                switch (msg.what) {
                case OPEN_CAMERA:
					try {
						Log.v(TAG, "start sleep 4s");  
						Thread.sleep(4000);
						Log.v(TAG, "end sleep 4s"); 
					} catch (InterruptedException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}

                    default:
                }
          
        }
    }

hander同步技巧 利用post之后的消息是最后完成的,实现同步。关键看waitDone的实现。带面精简Camera应用。

标签:handle同步技巧

原文地址:http://blog.csdn.net/langxianwenye/article/details/45366667

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!