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// TODO: There is sufficent similarity between this and the awaitable error listener that I should 29// extract a common base class. 30/** Implementation of {@link MediaPlayer.OnErrorListener} that we can wait for in tests. */ 31@ThreadSafe 32public class AwaitableCompletionListener implements MediaPlayer.OnCompletionListener { 33 private final BlockingQueue<Object> mQueue = new LinkedBlockingQueue<Object>(); 34 35 @Override 36 public void onCompletion(MediaPlayer mp) { 37 try { 38 mQueue.put(new Object()); 39 } catch (InterruptedException e) { 40 // This should not happen in practice, the queue is unbounded so this method will not 41 // block. 42 // If this thread is using interrupt to shut down, preserve interrupt status and return. 43 Thread.currentThread().interrupt(); 44 } 45 } 46 47 public void awaitOneCallback(long timeout, TimeUnit unit) throws InterruptedException, 48 TimeoutException { 49 if (mQueue.poll(timeout, unit) == null) { 50 throw new TimeoutException(); 51 } 52 } 53 54 public void assertNoMoreCallbacks() { 55 if (mQueue.peek() != null) { 56 throw new IllegalStateException("there was an unexpected callback on the queue"); 57 } 58 } 59} 60