1 /* 2 * Copyright (C) 2019 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 com.android.systemui.car; 18 19 import android.car.Car; 20 import android.content.Context; 21 22 import androidx.annotation.VisibleForTesting; 23 24 import java.util.ArrayList; 25 import java.util.List; 26 27 import javax.inject.Inject; 28 import javax.inject.Singleton; 29 30 /** Provides a common connection to the car service that can be shared. */ 31 @Singleton 32 public class CarServiceProvider { 33 34 private final Context mContext; 35 private final List<CarServiceOnConnectedListener> mListeners = new ArrayList<>(); 36 private Car mCar; 37 38 @Inject CarServiceProvider(Context context)39 public CarServiceProvider(Context context) { 40 mContext = context; 41 mCar = Car.createCar(mContext, /* handler= */ null, Car.CAR_WAIT_TIMEOUT_DO_NOT_WAIT, 42 (car, ready) -> { 43 mCar = car; 44 45 synchronized (mListeners) { 46 for (CarServiceOnConnectedListener listener : mListeners) { 47 if (ready) { 48 listener.onConnected(mCar); 49 } 50 } 51 } 52 }); 53 } 54 55 @VisibleForTesting CarServiceProvider(Context context, Car car)56 public CarServiceProvider(Context context, Car car) { 57 mContext = context; 58 mCar = car; 59 } 60 61 /** 62 * Let's other components hook into the connection to the car service. If we're already 63 * connected to the car service, the callback is immediately triggered. 64 */ addListener(CarServiceOnConnectedListener listener)65 public void addListener(CarServiceOnConnectedListener listener) { 66 if (mCar.isConnected()) { 67 listener.onConnected(mCar); 68 } 69 mListeners.add(listener); 70 } 71 72 /** 73 * Listener which is triggered when Car Service is connected. 74 */ 75 public interface CarServiceOnConnectedListener { 76 /** This will be called when the car service has successfully been connected. */ onConnected(Car car)77 void onConnected(Car car); 78 } 79 } 80