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 * is PR Ocessed. * * @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 is 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 auto-generated catch block E.printstacktrace ();} Default:}}}
The hander synchronization technique utilizes post messages to be completed at the end, enabling synchronization. The key to see the realization of Waitdone. Thin camera app with face.