1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.os; 18 19import android.os.Handler; 20import android.os.Looper; 21import android.os.Message; 22import android.os.MessageQueue.IdleHandler; 23 24abstract class TestHandlerThread { 25 private boolean mDone = false; 26 private boolean mSuccess = false; 27 private RuntimeException mFailure = null; 28 private Looper mLooper; 29 30 public abstract void go(); 31 32 public TestHandlerThread() { 33 } 34 35 public void doTest(long timeout) { 36 (new LooperThread()).start(); 37 38 synchronized (this) { 39 long now = System.currentTimeMillis(); 40 long endTime = now + timeout; 41 while (!mDone && now < endTime) { 42 try { 43 wait(endTime-now); 44 } 45 catch (InterruptedException e) { 46 } 47 now = System.currentTimeMillis(); 48 } 49 } 50 51 mLooper.quit(); 52 53 if (!mDone) { 54 throw new RuntimeException("test timed out"); 55 } 56 if (!mSuccess) { 57 throw mFailure; 58 } 59 } 60 61 public Looper getLooper() { 62 return mLooper; 63 } 64 65 public void success() { 66 synchronized (this) { 67 mSuccess = true; 68 quit(); 69 } 70 } 71 72 public void failure(RuntimeException failure) { 73 synchronized (this) { 74 mSuccess = false; 75 mFailure = failure; 76 quit(); 77 } 78 } 79 80 class LooperThread extends Thread { 81 public void run() { 82 Looper.prepare(); 83 mLooper = Looper.myLooper(); 84 go(); 85 Looper.loop(); 86 87 synchronized (TestHandlerThread.this) { 88 mDone = true; 89 if (!mSuccess && mFailure == null) { 90 mFailure = new RuntimeException("no failure exception set"); 91 } 92 TestHandlerThread.this.notifyAll(); 93 } 94 } 95 96 } 97 98 private void quit() { 99 synchronized (this) { 100 mDone = true; 101 notifyAll(); 102 } 103 } 104} 105