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 17 package android.car.apitest; 18 19 import android.content.ComponentName; 20 import android.content.ServiceConnection; 21 import android.os.IBinder; 22 import android.os.Looper; 23 import android.car.Car; 24 import android.test.AndroidTestCase; 25 26 import java.util.concurrent.Semaphore; 27 import java.util.concurrent.TimeUnit; 28 29 public 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 assertMainThread()37 protected static void assertMainThread() { 38 assertTrue(Looper.getMainLooper().isCurrentThread()); 39 } 40 41 @Override setUp()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 tearDown()50 protected void tearDown() throws Exception { 51 super.tearDown(); 52 mCar.disconnect(); 53 } 54 getCar()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 waitForConnection(long timeoutMs)62 public void waitForConnection(long timeoutMs) throws InterruptedException { 63 mConnectionWait.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS); 64 } 65 66 @Override onServiceConnected(ComponentName name, IBinder service)67 public void onServiceConnected(ComponentName name, IBinder service) { 68 assertMainThread(); 69 mConnectionWait.release(); 70 } 71 72 @Override onServiceDisconnected(ComponentName name)73 public void onServiceDisconnected(ComponentName name) { 74 assertMainThread(); 75 } 76 } 77 } 78