1 /* 2 * Copyright (C) 2016 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.cts; 18 19 import static org.junit.Assert.assertTrue; 20 import static org.junit.Assume.assumeTrue; 21 22 import android.car.Car; 23 import android.content.ComponentName; 24 import android.content.Context; 25 import android.content.ServiceConnection; 26 import android.os.IBinder; 27 import android.os.Looper; 28 29 import androidx.test.InstrumentationRegistry; 30 31 import com.android.compatibility.common.util.FeatureUtil; 32 33 import org.junit.After; 34 35 import java.util.concurrent.Semaphore; 36 import java.util.concurrent.TimeUnit; 37 38 public abstract class CarApiTestBase { 39 protected static final long DEFAULT_WAIT_TIMEOUT_MS = 1000; 40 41 private Car mCar; 42 43 private final DefaultServiceConnectionListener mConnectionListener = 44 new DefaultServiceConnectionListener(); 45 46 protected void assertMainThread() { 47 assertTrue(Looper.getMainLooper().isCurrentThread()); 48 } 49 50 protected void setUp() throws Exception { 51 assumeTrue(FeatureUtil.isAutomotive()); 52 53 Context context = 54 InstrumentationRegistry.getInstrumentation().getTargetContext(); 55 mCar = Car.createCar(context, mConnectionListener, null); 56 mCar.connect(); 57 mConnectionListener.waitForConnection(DEFAULT_WAIT_TIMEOUT_MS); 58 } 59 60 @After 61 public void disconnectCar() throws Exception { 62 if (mCar != null) { 63 mCar.disconnect(); 64 } 65 } 66 67 protected synchronized Car getCar() { 68 return mCar; 69 } 70 71 protected class DefaultServiceConnectionListener implements ServiceConnection { 72 private final Semaphore mConnectionWait = new Semaphore(0); 73 74 public void waitForConnection(long timeoutMs) throws InterruptedException { 75 mConnectionWait.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS); 76 } 77 78 @Override 79 public void onServiceDisconnected(ComponentName name) { 80 assertMainThread(); 81 } 82 83 @Override 84 public void onServiceConnected(ComponentName name, IBinder service) { 85 assertMainThread(); 86 mConnectionWait.release(); 87 } 88 } 89 } 90