1/* 2 * Copyright (C) 2015 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.car.apitest; 18 19import android.content.ComponentName; 20import android.content.ServiceConnection; 21import android.os.IBinder; 22import android.os.Looper; 23import android.car.Car; 24import android.test.AndroidTestCase; 25 26import java.util.concurrent.Semaphore; 27import java.util.concurrent.TimeUnit; 28 29public class CarApiTestBase extends AndroidTestCase { 30 protected static final long DEFAULT_WAIT_TIMEOUT_MS = 1000; 31 32 private Car mCar; 33 34 private final DefaultServiceConnectionListener mConnectionListener = 35 new DefaultServiceConnectionListener(); 36 37 protected static void assertMainThread() { 38 assertTrue(Looper.getMainLooper().isCurrentThread()); 39 } 40 41 @Override 42 protected void setUp() throws Exception { 43 super.setUp(); 44 mCar = Car.createCar(getContext(), mConnectionListener); 45 mCar.connect(); 46 mConnectionListener.waitForConnection(DEFAULT_WAIT_TIMEOUT_MS); 47 } 48 49 @Override 50 protected void tearDown() throws Exception { 51 super.tearDown(); 52 mCar.disconnect(); 53 } 54 55 protected synchronized Car getCar() { 56 return mCar; 57 } 58 59 protected static class DefaultServiceConnectionListener implements ServiceConnection { 60 private final Semaphore mConnectionWait = new Semaphore(0); 61 62 public void waitForConnection(long timeoutMs) throws InterruptedException { 63 mConnectionWait.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS); 64 } 65 66 @Override 67 public void onServiceConnected(ComponentName name, IBinder service) { 68 assertMainThread(); 69 mConnectionWait.release(); 70 } 71 72 @Override 73 public void onServiceDisconnected(ComponentName name) { 74 assertMainThread(); 75 } 76 } 77} 78