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