1/* 2 * Copyright (C) 2011 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 com.android.ex.variablespeed; 18 19import android.media.MediaPlayer; 20 21import java.util.concurrent.BlockingQueue; 22import java.util.concurrent.LinkedBlockingQueue; 23import java.util.concurrent.TimeUnit; 24import java.util.concurrent.TimeoutException; 25 26import javax.annotation.concurrent.ThreadSafe; 27 28/** Implementation of {@link MediaPlayer.OnCompletionListener} that we can wait for in tests. */ 29@ThreadSafe 30public class AwaitableErrorListener implements MediaPlayer.OnErrorListener { 31 private final BlockingQueue<Object> mQueue = new LinkedBlockingQueue<Object>(); 32 private volatile boolean mOnErrorReturnValue = true; 33 34 @Override 35 public boolean onError(MediaPlayer mp, int what, int extra) { 36 addAnObjectToTheQueue(); 37 return mOnErrorReturnValue; 38 } 39 40 public void setOnErrorReturnValue(boolean value) { 41 mOnErrorReturnValue = value; 42 } 43 44 private void addAnObjectToTheQueue() { 45 try { 46 mQueue.put(new Object()); 47 } catch (InterruptedException e) { 48 // This should not happen in practice, the queue is unbounded so this method will not 49 // block. 50 // If this thread is using interrupt to shut down, preserve interrupt status and return. 51 Thread.currentThread().interrupt(); 52 } 53 } 54 55 public void awaitOneCallback(long timeout, TimeUnit unit) throws InterruptedException, 56 TimeoutException { 57 if (mQueue.poll(timeout, unit) == null) { 58 throw new TimeoutException(); 59 } 60 } 61 62 public void assertNoMoreCallbacks() { 63 if (mQueue.peek() != null) { 64 throw new IllegalStateException("there was an unexpected callback on the queue"); 65 } 66 } 67} 68