• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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;
18 
19 import static android.car.CarLibLog.TAG_CAR;
20 
21 import android.annotation.IntDef;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.RequiresPermission;
25 import android.annotation.SdkConstant;
26 import android.annotation.SdkConstant.SdkConstantType;
27 import android.annotation.SuppressLint;
28 import android.annotation.SystemApi;
29 import android.annotation.TestApi;
30 import android.app.Activity;
31 import android.app.Service;
32 import android.car.admin.CarDevicePolicyManager;
33 import android.car.annotation.MandatoryFeature;
34 import android.car.annotation.OptionalFeature;
35 import android.car.cluster.CarInstrumentClusterManager;
36 import android.car.cluster.ClusterActivityState;
37 import android.car.cluster.ClusterHomeManager;
38 import android.car.content.pm.CarPackageManager;
39 import android.car.diagnostic.CarDiagnosticManager;
40 import android.car.drivingstate.CarDrivingStateManager;
41 import android.car.drivingstate.CarUxRestrictionsManager;
42 import android.car.evs.CarEvsManager;
43 import android.car.hardware.CarSensorManager;
44 import android.car.hardware.CarVendorExtensionManager;
45 import android.car.hardware.cabin.CarCabinManager;
46 import android.car.hardware.hvac.CarHvacManager;
47 import android.car.hardware.power.CarPowerManager;
48 import android.car.hardware.property.CarPropertyManager;
49 import android.car.hardware.property.ICarProperty;
50 import android.car.input.CarInputManager;
51 import android.car.media.CarAudioManager;
52 import android.car.media.CarMediaIntents;
53 import android.car.media.CarMediaManager;
54 import android.car.navigation.CarNavigationStatusManager;
55 import android.car.occupantawareness.OccupantAwarenessManager;
56 import android.car.storagemonitoring.CarStorageMonitoringManager;
57 import android.car.telemetry.CarTelemetryManager;
58 import android.car.test.CarTestManagerBinderWrapper;
59 import android.car.user.CarUserManager;
60 import android.car.vms.VmsClientManager;
61 import android.car.vms.VmsSubscriberManager;
62 import android.car.watchdog.CarWatchdogManager;
63 import android.content.ComponentName;
64 import android.content.Context;
65 import android.content.ContextWrapper;
66 import android.content.Intent;
67 import android.content.ServiceConnection;
68 import android.content.pm.PackageManager;
69 import android.os.Handler;
70 import android.os.IBinder;
71 import android.os.Looper;
72 import android.os.Process;
73 import android.os.RemoteException;
74 import android.os.ServiceManager;
75 import android.os.TransactionTooLargeException;
76 import android.os.UserHandle;
77 import android.util.Log;
78 
79 import com.android.car.internal.common.CommonConstants;
80 import com.android.internal.annotations.GuardedBy;
81 import com.android.internal.annotations.VisibleForTesting;
82 
83 import java.lang.annotation.ElementType;
84 import java.lang.annotation.Retention;
85 import java.lang.annotation.RetentionPolicy;
86 import java.lang.annotation.Target;
87 import java.lang.reflect.Constructor;
88 import java.lang.reflect.InvocationTargetException;
89 import java.util.Collections;
90 import java.util.HashMap;
91 import java.util.List;
92 import java.util.Objects;
93 
94 /**
95  *   Top level car API for embedded Android Auto deployments.
96  *   This API works only for devices with {@link PackageManager#FEATURE_AUTOMOTIVE}
97  *   Calling this API on a device with no such feature will lead to an exception.
98  */
99 public final class Car {
100 
101     /**
102      * Binder service name of car service registered to service manager.
103      *
104      * @hide
105      */
106     public static final String CAR_SERVICE_BINDER_SERVICE_NAME = "car_service";
107 
108     /**
109      * This represents AndroidManifest meta-data to tell that {@code Activity} is optimized for
110      * driving distraction.
111      *
112      * <p>Activities without this meta-data can be blocked while car is in moving / driving state.
113      *
114      * <p>Note that having this flag does not guarantee that the {@code Activity} will be always
115      * allowed for all driving states.
116      *
117      * <p>For this meta-data, android:value can be {@code true} (=optimized) or {@code false}.
118      *
119      * <p>Example usage:
120      * <xml><meta-data android:name="distractionOptimized" android:value="true"/></xml>
121      */
122     @SuppressLint("IntentName")
123     public static final String META_DATA_DISTRACTION_OPTIMIZED = "distractionOptimized";
124 
125     /**
126      * This represents AndroidManifest meta-data to tell that {@code Application} requires specific
127      * car features to work.
128      *
129      * <p>Apps like launcher or installer app can use this information to filter out apps
130      * not usable in a specific car. This meta-data is not necessary for mandatory features.
131      *
132      * <p>For this meta-data, android:value should contain the feature name string defined by
133      * (@link android.car.annotation.OptionalFeature} or
134      * {@link android.car.annotation.ExperimentalFeature} annotations.
135      *
136      * <p>Example usage:
137      * <xml><meta-data android:name="requires-car-feature" android:value="diagnostic"/></xml>
138      */
139     @SuppressLint("IntentName")
140     public static final String META_DATA_REQUIRES_CAR_FEATURE = "requires-car-feature";
141 
142     /**
143      * Service name for {@link CarSensorManager}, to be used in {@link #getCarManager(String)}.
144      *
145      * @deprecated  {@link CarSensorManager} is deprecated. Use {@link CarPropertyManager} instead.
146      */
147     @MandatoryFeature
148     @Deprecated
149     public static final String SENSOR_SERVICE = "sensor";
150 
151     /** Service name for {@link CarInfoManager}, to be used in {@link #getCarManager(String)}. */
152     @MandatoryFeature
153     public static final String INFO_SERVICE = "info";
154 
155     /** Service name for {@link CarAppFocusManager}. */
156     @MandatoryFeature
157     public static final String APP_FOCUS_SERVICE = "app_focus";
158 
159     /** Service name for {@link CarPackageManager} */
160     @MandatoryFeature
161     public static final String PACKAGE_SERVICE = "package";
162 
163     /** Service name for {@link CarAudioManager} */
164     @MandatoryFeature
165     public static final String AUDIO_SERVICE = "audio";
166 
167     /** Service name for {@link CarNavigationStatusManager} */
168     @OptionalFeature
169     public static final String CAR_NAVIGATION_SERVICE = "car_navigation_service";
170 
171     /** Service name for {@link CarOccupantZoneManager} */
172     @MandatoryFeature
173     public static final String CAR_OCCUPANT_ZONE_SERVICE = "car_occupant_zone_service";
174 
175     /**
176      * Service name for {@link CarUserManager}
177      *
178      * @hide
179      */
180     @MandatoryFeature
181     @SystemApi
182     @TestApi
183     public static final String CAR_USER_SERVICE = "car_user_service";
184 
185     /**
186      * Service name for {@link CarDevicePolicyManager}
187      *
188      * @hide
189      */
190     @MandatoryFeature
191     @SystemApi
192     @TestApi
193     public static final String CAR_DEVICE_POLICY_SERVICE = "car_device_policy_service";
194 
195     /**
196      * Service name for {@link CarInstrumentClusterManager}
197      *
198      * @deprecated CarInstrumentClusterManager is being deprecated
199      * @hide
200      */
201     @OptionalFeature
202     @Deprecated
203     public static final String CAR_INSTRUMENT_CLUSTER_SERVICE = "cluster_service";
204 
205     /**
206      * Service name for {@link CarCabinManager}.
207      *
208      * @deprecated {@link CarCabinManager} is deprecated. Use {@link CarPropertyManager} instead.
209      * @hide
210      */
211     @MandatoryFeature
212     @Deprecated
213     @SystemApi
214     public static final String CABIN_SERVICE = "cabin";
215 
216     /**
217      * @hide
218      */
219     @OptionalFeature
220     @SystemApi
221     public static final String DIAGNOSTIC_SERVICE = "diagnostic";
222 
223     /**
224      * Service name for {@link CarHvacManager}
225      * @deprecated {@link CarHvacManager} is deprecated. Use {@link CarPropertyManager} instead.
226      * @hide
227      */
228     @MandatoryFeature
229     @Deprecated
230     @SystemApi
231     public static final String HVAC_SERVICE = "hvac";
232 
233     /**
234      * Service name for {@link CarPowerManager}
235      */
236     @MandatoryFeature
237     public static final String POWER_SERVICE = "power";
238 
239     /**
240      * @hide
241      */
242     @MandatoryFeature
243     @SystemApi
244     public static final String PROJECTION_SERVICE = "projection";
245 
246     /**
247      * Service name for {@link CarPropertyManager}
248      */
249     @MandatoryFeature
250     public static final String PROPERTY_SERVICE = "property";
251 
252     /**
253      * Service name for {@link CarVendorExtensionManager}
254      *
255      * @deprecated {@link CarVendorExtensionManager} is deprecated.
256      * Use {@link CarPropertyManager} instead.
257      * @hide
258      */
259     @MandatoryFeature
260     @Deprecated
261     @SystemApi
262     public static final String VENDOR_EXTENSION_SERVICE = "vendor_extension";
263 
264     /**
265      * @hide
266      */
267     @MandatoryFeature
268     public static final String BLUETOOTH_SERVICE = "car_bluetooth";
269 
270     /**
271      * Service name for {@link VmsClientManager}
272      *
273      * @hide
274      */
275     @OptionalFeature
276     @SystemApi
277     public static final String VEHICLE_MAP_SERVICE = "vehicle_map_service";
278 
279     /**
280      * Service name for {@link VmsSubscriberManager}
281      *
282      * @deprecated {@link VmsSubscriberManager} is deprecated. Use {@link VmsClientManager} instead.
283      * @hide
284      */
285     @OptionalFeature
286     @Deprecated
287     @SystemApi
288     public static final String VMS_SUBSCRIBER_SERVICE = "vehicle_map_subscriber_service";
289 
290     /**
291      * Service name for {@link CarDrivingStateManager}
292      * @hide
293      */
294     @MandatoryFeature
295     @SystemApi
296     public static final String CAR_DRIVING_STATE_SERVICE = "drivingstate";
297 
298     /**
299      * Service name for {@link CarUxRestrictionsManager}
300      */
301     public static final String CAR_UX_RESTRICTION_SERVICE = "uxrestriction";
302 
303     /** @hide */
304     @OptionalFeature
305     @SystemApi
306     public static final String OCCUPANT_AWARENESS_SERVICE = "occupant_awareness";
307 
308     /**
309      * Service name for {@link android.car.media.CarMediaManager}
310      * @hide
311      */
312     @MandatoryFeature
313     @SystemApi
314     public static final String CAR_MEDIA_SERVICE = "car_media";
315 
316     /**
317      *
318      * Service name for {@link android.car.CarBugreportManager}
319      * @hide
320      */
321     @MandatoryFeature
322     public static final String CAR_BUGREPORT_SERVICE = "car_bugreport";
323 
324     /**
325      * @hide
326      */
327     @OptionalFeature
328     @SystemApi
329     public static final String STORAGE_MONITORING_SERVICE = "storage_monitoring";
330 
331     /**
332      * Service name for {@link android.car.watchdog.CarWatchdogManager}
333      */
334     @MandatoryFeature
335     public static final String CAR_WATCHDOG_SERVICE = "car_watchdog";
336 
337     /**
338      * @hide
339      */
340     @MandatoryFeature
341     @SystemApi
342     public static final String CAR_INPUT_SERVICE = "android.car.input";
343 
344     /**
345      * @hide
346      */
347     @OptionalFeature
348     public static final String CLUSTER_HOME_SERVICE = "cluster_home_service";
349 
350     /**
351      * Service for testing. This is system app only feature.
352      * Service name for {@link CarTestManager}, to be used in {@link #getCarManager(String)}.
353      * @hide
354      */
355     @MandatoryFeature
356     @SystemApi
357     public static final String TEST_SERVICE = "car-service-test";
358 
359     /**
360      * Service name for {@link android.car.evs.CarEvsManager}
361      *
362      * @hide
363      */
364     @OptionalFeature
365     @SystemApi
366     public static final String CAR_EVS_SERVICE = "car_evs_service";
367 
368     /**
369      * Service name for {@link android.car.telemetry.CarTelemetryManager}
370      *
371      * @hide
372      */
373     @OptionalFeature
374     public static final String CAR_TELEMETRY_SERVICE = "car_telemetry_service";
375 
376     /** Permission necessary to access car's mileage information.
377      *  @hide
378      */
379     @SystemApi
380     public static final String PERMISSION_MILEAGE = "android.car.permission.CAR_MILEAGE";
381 
382     /** Permission necessary to access car's energy information. */
383     public static final String PERMISSION_ENERGY = "android.car.permission.CAR_ENERGY";
384 
385     /**
386      * Permission necessary to change value of car's range remaining.
387      * @hide
388      */
389     @SystemApi
390     public static final String PERMISSION_ADJUST_RANGE_REMAINING =
391             "android.car.permission.ADJUST_RANGE_REMAINING";
392 
393     /** Permission necessary to access car's VIN information */
394     public static final String PERMISSION_IDENTIFICATION =
395             "android.car.permission.CAR_IDENTIFICATION";
396 
397     /** Permission necessary to access car's speed. */
398     public static final String PERMISSION_SPEED = "android.car.permission.CAR_SPEED";
399 
400     /** Permission necessary to access car's dynamics state.
401      *  @hide
402      */
403     @SystemApi
404     public static final String PERMISSION_CAR_DYNAMICS_STATE =
405             "android.car.permission.CAR_DYNAMICS_STATE";
406 
407     /** Permission necessary to access car's fuel door and ev charge port. */
408     public static final String PERMISSION_ENERGY_PORTS = "android.car.permission.CAR_ENERGY_PORTS";
409 
410     /**
411      * Permission necessary to control car's fuel door and ev charge port.
412      * @hide
413      */
414     @SystemApi
415     public static final String PERMISSION_CONTROL_ENERGY_PORTS =
416             "android.car.permission.CONTROL_CAR_ENERGY_PORTS";
417 
418     /**
419      * Permission necessary to read car's exterior lights information.
420      *  @hide
421      */
422     @SystemApi
423     public static final String PERMISSION_EXTERIOR_LIGHTS =
424             "android.car.permission.CAR_EXTERIOR_LIGHTS";
425 
426     /**
427      * Permission necessary to read car's interior lights information.
428      */
429     public static final String PERMISSION_READ_INTERIOR_LIGHTS =
430             "android.car.permission.READ_CAR_INTERIOR_LIGHTS";
431 
432     /** Permission necessary to control car's exterior lights.
433      *  @hide
434      */
435     @SystemApi
436     public static final String PERMISSION_CONTROL_EXTERIOR_LIGHTS =
437             "android.car.permission.CONTROL_CAR_EXTERIOR_LIGHTS";
438 
439     /**
440      * Permission necessary to control car's interior lights.
441      */
442     public static final String PERMISSION_CONTROL_INTERIOR_LIGHTS =
443             "android.car.permission.CONTROL_CAR_INTERIOR_LIGHTS";
444 
445     /** Permission necessary to access car's powertrain information.*/
446     public static final String PERMISSION_POWERTRAIN = "android.car.permission.CAR_POWERTRAIN";
447 
448     /**
449      * Permission necessary to change car audio volume through {@link CarAudioManager}.
450      */
451     public static final String PERMISSION_CAR_CONTROL_AUDIO_VOLUME =
452             "android.car.permission.CAR_CONTROL_AUDIO_VOLUME";
453 
454     /**
455      * Permission necessary to change car audio settings through {@link CarAudioManager}.
456      */
457     public static final String PERMISSION_CAR_CONTROL_AUDIO_SETTINGS =
458             "android.car.permission.CAR_CONTROL_AUDIO_SETTINGS";
459 
460     /**
461      * Permission necessary to receive full audio ducking events from car audio focus handler.
462      *
463      * @hide
464      */
465     @SystemApi
466     public static final String PERMISSION_RECEIVE_CAR_AUDIO_DUCKING_EVENTS =
467             "android.car.permission.RECEIVE_CAR_AUDIO_DUCKING_EVENTS";
468 
469     /**
470      * Permission necessary to use {@link CarNavigationStatusManager}.
471      */
472     public static final String PERMISSION_CAR_NAVIGATION_MANAGER =
473             "android.car.permission.CAR_NAVIGATION_MANAGER";
474 
475     /**
476      * Permission necessary to start activities in the instrument cluster through
477      * {@link CarInstrumentClusterManager}
478      *
479      * @hide
480      */
481     @SystemApi
482     public static final String PERMISSION_CAR_INSTRUMENT_CLUSTER_CONTROL =
483             "android.car.permission.CAR_INSTRUMENT_CLUSTER_CONTROL";
484 
485     /**
486      * Application must have this permission in order to be launched in the instrument cluster
487      * display.
488      *
489      * @hide
490      */
491     public static final String PERMISSION_CAR_DISPLAY_IN_CLUSTER =
492             "android.car.permission.CAR_DISPLAY_IN_CLUSTER";
493 
494     /** Permission necessary to use {@link CarInfoManager}. */
495     public static final String PERMISSION_CAR_INFO = "android.car.permission.CAR_INFO";
496 
497     /**
498      * Permission necessary to read information of vendor properties' permissions.
499      * @hide
500      */
501     @SystemApi
502     public static final String PERMISSION_READ_CAR_VENDOR_PERMISSION_INFO =
503             "android.car.permission.READ_CAR_VENDOR_PERMISSION_INFO";
504 
505     /** Permission necessary to read temperature of car's exterior environment. */
506     public static final String PERMISSION_EXTERIOR_ENVIRONMENT =
507             "android.car.permission.CAR_EXTERIOR_ENVIRONMENT";
508 
509     /**
510      * Permission necessary to access car specific communication channel.
511      * @hide
512      */
513     @SystemApi
514     public static final String PERMISSION_VENDOR_EXTENSION =
515             "android.car.permission.CAR_VENDOR_EXTENSION";
516 
517     /**
518      * @hide
519      */
520     @SystemApi
521     public static final String PERMISSION_CONTROL_APP_BLOCKING =
522             "android.car.permission.CONTROL_APP_BLOCKING";
523 
524     /**
525      * Permission necessary to access car's engine information.
526      * @hide
527      */
528     @SystemApi
529     public static final String PERMISSION_CAR_ENGINE_DETAILED =
530             "android.car.permission.CAR_ENGINE_DETAILED";
531 
532     /**
533      * Permission necessary to access car's tire pressure information.
534      * @hide
535      */
536     @SystemApi
537     public static final String PERMISSION_TIRES = "android.car.permission.CAR_TIRES";
538 
539     /**
540      * Permission necessary to access car's property {@link VehiclePropertyIds#EPOCH_TIME}.
541      * @hide
542      */
543     @SystemApi
544     public static final String PERMISSION_CAR_EPOCH_TIME = "android.car.permission.CAR_EPOCH_TIME";
545 
546     /**
547      * Permission necessary to access car's property
548      * {@link VehiclePropertyIds#STORAGE_ENCRYPTION_BINDING_SEED}.
549      * @hide
550      */
551     @SystemApi
552     public static final String PERMISSION_STORAGE_ENCRYPTION_BINDING_SEED =
553             "android.car.permission.STORAGE_ENCRYPTION_BINDING_SEED";
554 
555     /**
556      * Permission necessary to access car's steering angle information.
557      */
558     public static final String PERMISSION_READ_STEERING_STATE =
559             "android.car.permission.READ_CAR_STEERING";
560 
561     /**
562      * Permission necessary to read and write display units for distance, fuel volume, tire pressure
563      * and ev battery.
564      */
565     public static final String PERMISSION_READ_DISPLAY_UNITS =
566             "android.car.permission.READ_CAR_DISPLAY_UNITS";
567 
568     /**
569      * Permission necessary to control display units for distance, fuel volume, tire pressure
570      * and ev battery.
571      */
572     public static final String PERMISSION_CONTROL_DISPLAY_UNITS =
573             "android.car.permission.CONTROL_CAR_DISPLAY_UNITS";
574 
575     /**
576      * Permission necessary to control car's door.
577      * @hide
578      */
579     @SystemApi
580     public static final String PERMISSION_CONTROL_CAR_DOORS =
581             "android.car.permission.CONTROL_CAR_DOORS";
582 
583     /**
584      * Permission necessary to control car's windows.
585      * @hide
586      */
587     @SystemApi
588     public static final String PERMISSION_CONTROL_CAR_WINDOWS =
589             "android.car.permission.CONTROL_CAR_WINDOWS";
590 
591     /**
592      * Permission necessary to control car's seats.
593      * @hide
594      */
595     @SystemApi
596     public static final String PERMISSION_CONTROL_CAR_SEATS =
597             "android.car.permission.CONTROL_CAR_SEATS";
598 
599     /**
600      * Permission necessary to control car's mirrors.
601      * @hide
602      */
603     @SystemApi
604     public static final String PERMISSION_CONTROL_CAR_MIRRORS =
605             "android.car.permission.CONTROL_CAR_MIRRORS";
606 
607     /**
608      * Permission necessary to access Car HVAC APIs.
609      * @hide
610      */
611     @SystemApi
612     public static final String PERMISSION_CONTROL_CAR_CLIMATE =
613             "android.car.permission.CONTROL_CAR_CLIMATE";
614 
615     /**
616      * Permission necessary to access restrictive car power management APIs.
617      * @hide
618      */
619     @SystemApi
620     public static final String PERMISSION_CAR_POWER = "android.car.permission.CAR_POWER";
621 
622     /**
623      * Permission necessary to read the current power policy or be notified of power policy change.
624      */
625     public static final String PERMISSION_READ_CAR_POWER_POLICY =
626             "android.car.permission.READ_CAR_POWER_POLICY";
627 
628     /**
629      * Permission necessary to apply a new power policy.
630      * @hide
631      */
632     @SystemApi
633     public static final String PERMISSION_CONTROL_CAR_POWER_POLICY =
634             "android.car.permission.CONTROL_CAR_POWER_POLICY";
635 
636     /**
637      * Permission necessary to access Car PROJECTION system APIs.
638      * @hide
639      */
640     @SystemApi
641     public static final String PERMISSION_CAR_PROJECTION = "android.car.permission.CAR_PROJECTION";
642 
643     /**
644      * Permission necessary to access projection status.
645      * @hide
646      */
647     @SystemApi
648     public static final String PERMISSION_CAR_PROJECTION_STATUS =
649             "android.car.permission.ACCESS_CAR_PROJECTION_STATUS";
650 
651     /**
652      * Permission necessary to mock vehicle hal for testing.
653      * @hide
654      * @deprecated mocking vehicle HAL in car service is no longer supported.
655      */
656     @Deprecated
657     @SystemApi
658     public static final String PERMISSION_MOCK_VEHICLE_HAL =
659             "android.car.permission.CAR_MOCK_VEHICLE_HAL";
660 
661     /**
662      * Permission necessary to access CarTestService.
663      * @hide
664      */
665     @SystemApi
666     public static final String PERMISSION_CAR_TEST_SERVICE =
667             "android.car.permission.CAR_TEST_SERVICE";
668 
669     /**
670      * Permission necessary to access CarDrivingStateService to get a Car's driving state.
671      * @hide
672      */
673     @SystemApi
674     public static final String PERMISSION_CAR_DRIVING_STATE =
675             "android.car.permission.CAR_DRIVING_STATE";
676 
677     /**
678      * Permission necessary to access VMS client service.
679      *
680      * @hide
681      */
682     public static final String PERMISSION_BIND_VMS_CLIENT =
683             "android.car.permission.BIND_VMS_CLIENT";
684 
685     /**
686      * Permissions necessary to access VMS publisher APIs.
687      *
688      * @hide
689      */
690     @SystemApi
691     public static final String PERMISSION_VMS_PUBLISHER = "android.car.permission.VMS_PUBLISHER";
692 
693     /**
694      * Permissions necessary to access VMS subscriber APIs.
695      *
696      * @hide
697      */
698     @SystemApi
699     public static final String PERMISSION_VMS_SUBSCRIBER = "android.car.permission.VMS_SUBSCRIBER";
700 
701     /**
702      * Permissions necessary to read diagnostic information, including vendor-specific bits.
703      *
704      * @hide
705      */
706     @SystemApi
707     public static final String PERMISSION_CAR_DIAGNOSTIC_READ_ALL =
708             "android.car.permission.CAR_DIAGNOSTICS";
709 
710     /**
711      * Permissions necessary to clear diagnostic information.
712      *
713      * @hide
714      */
715     @SystemApi
716     public static final String PERMISSION_CAR_DIAGNOSTIC_CLEAR =
717             "android.car.permission.CLEAR_CAR_DIAGNOSTICS";
718 
719     /**
720      * Permission necessary to configure UX restrictions through {@link CarUxRestrictionsManager}.
721      *
722      * @hide
723      */
724     public static final String PERMISSION_CAR_UX_RESTRICTIONS_CONFIGURATION =
725             "android.car.permission.CAR_UX_RESTRICTIONS_CONFIGURATION";
726 
727     /**
728      * Permission necessary to listen to occupant awareness state {@link OccupantAwarenessManager}.
729      *
730      * @hide
731      */
732     @SystemApi
733     public static final String PERMISSION_READ_CAR_OCCUPANT_AWARENESS_STATE =
734             "android.car.permission.READ_CAR_OCCUPANT_AWARENESS_STATE";
735 
736     /**
737      * Permission necessary to access private display id.
738      *
739      * @hide
740      */
741     @SystemApi
742     public static final String ACCESS_PRIVATE_DISPLAY_ID =
743             "android.car.permission.ACCESS_PRIVATE_DISPLAY_ID";
744 
745     /**
746      * @deprecated This permission is not used by any service.
747      *
748      * @hide
749      */
750     @SystemApi
751     public static final String PERMISSION_CONTROL_CAR_OCCUPANT_AWARENESS_SYSTEM =
752             "android.car.permission.CONTROL_CAR_OCCUPANT_AWARENESS_SYSTEM";
753 
754     /**
755      * Permissions necessary to clear diagnostic information.
756      *
757      * @hide
758      */
759     @SystemApi
760     public static final String PERMISSION_STORAGE_MONITORING =
761             "android.car.permission.STORAGE_MONITORING";
762 
763     /**
764      * Permission necessary to dynamically enable / disable optional car features.
765      *
766      * @hide
767      */
768     @SystemApi
769     public static final String PERMISSION_CONTROL_CAR_FEATURES =
770             "android.car.permission.CONTROL_CAR_FEATURES";
771 
772     /**
773      * Permission necessary to be car watchdog clients.
774      *
775      * @hide
776      */
777     @SystemApi
778     public static final String PERMISSION_USE_CAR_WATCHDOG =
779             "android.car.permission.USE_CAR_WATCHDOG";
780 
781     /**
782      * Permission necessary to monitor Car input events.
783      *
784      * @hide
785      */
786     @SystemApi
787     public static final String PERMISSION_CAR_MONITOR_INPUT =
788             "android.car.permission.CAR_MONITOR_INPUT";
789 
790     /**
791      * Permission necessary to request CarEvsService to launch the special activity to show the
792      * camera preview.
793      *
794      * @hide
795      */
796     @SystemApi
797     public static final String PERMISSION_REQUEST_CAR_EVS_ACTIVITY =
798             "android.car.permission.REQUEST_CAR_EVS_ACTIVITY";
799 
800     /**
801      * Permission necessary to control the special activity to show the camera preview.
802      *
803      * @hide
804      */
805     @SystemApi
806     public static final String PERMISSION_CONTROL_CAR_EVS_ACTIVITY =
807             "android.car.permission.CONTROL_CAR_EVS_ACTIVITY";
808 
809     /**
810      * Permission necessary to use the camera streams via CarEvsService.
811      *
812      * @hide
813      */
814     @SystemApi
815     public static final String PERMISSION_USE_CAR_EVS_CAMERA =
816             "android.car.permission.USE_CAR_EVS_CAMERA";
817 
818     /**
819      * Permission necessary to monitor the status of CarEvsService.
820      *
821      * @hide
822      */
823     @SystemApi
824     public static final String PERMISSION_MONITOR_CAR_EVS_STATUS =
825             "android.car.permission.MONITOR_CAR_EVS_STATUS";
826 
827     /**
828      * Permission necessary to use the CarTelemetryService.
829      *
830      * @hide
831      */
832     public static final String PERMISSION_USE_CAR_TELEMETRY_SERVICE =
833             "android.car.permission.USE_CAR_TELEMETRY_SERVICE";
834 
835     /**
836      * Type of car connection: platform runs directly in car.
837      *
838      * @deprecated connection type constants are no longer used
839      */
840     @Deprecated
841     public static final int CONNECTION_TYPE_EMBEDDED = 5;
842 
843     /**
844      * Permission necessary to be able to render template-based UI metadata on behalf of another
845      * application.
846      *
847      * @hide
848      */
849     @SystemApi
850     public static final String PERMISSION_TEMPLATE_RENDERER =
851             "android.car.permission.TEMPLATE_RENDERER";
852 
853     /**
854      * Permission necessary to set or retrieve car watchdog configurations.
855      *
856      * @hide
857      */
858     @SystemApi
859     public static final String PERMISSION_CONTROL_CAR_WATCHDOG_CONFIG =
860             "android.car.permission.CONTROL_CAR_WATCHDOG_CONFIG";
861 
862     /**
863      * Permission necessary to collect metrics from car watchdog.
864      *
865      * @hide
866      */
867     @SystemApi
868     public static final String PERMISSION_COLLECT_CAR_WATCHDOG_METRICS =
869             "android.car.permission.COLLECT_CAR_WATCHDOG_METRICS";
870 
871     /** @hide */
872     @IntDef({CONNECTION_TYPE_EMBEDDED})
873     @Retention(RetentionPolicy.SOURCE)
874     public @interface ConnectionType {}
875 
876     /**
877      * @deprecated Use {@link CarMediaIntents#ACTION_MEDIA_TEMPLATE} instead.
878      */
879     @Deprecated
880     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
881     public static final String CAR_INTENT_ACTION_MEDIA_TEMPLATE =
882             "android.car.intent.action.MEDIA_TEMPLATE";
883 
884     /**
885      * @deprecated Use {@link CarMediaIntents#EXTRA_MEDIA_COMPONENT} instead.
886      */
887     @Deprecated
888     public static final String CAR_EXTRA_MEDIA_COMPONENT =
889             "android.car.intent.extra.MEDIA_COMPONENT";
890 
891     /**
892      *
893      * @deprecated Use {@link #CAR_EXTRA_MEDIA_COMPONENT} instead.
894      * @removed Using this for specifying MediaBrowserService was not supported since API level 29
895      * and above. Apps must use {@link #CAR_EXTRA_MEDIA_COMPONENT} instead.
896      */
897     @Deprecated
898     public static final String CAR_EXTRA_MEDIA_PACKAGE = "android.car.intent.extra.MEDIA_PACKAGE";
899 
900     /**
901      * Used as a string extra field of media session to specify the service corresponding to the
902      * session.
903      */
904     public static final String CAR_EXTRA_BROWSE_SERVICE_FOR_SESSION =
905             "android.media.session.BROWSE_SERVICE";
906 
907     /** @hide */
908     public static final String CAR_SERVICE_INTERFACE_NAME = CommonConstants.CAR_SERVICE_INTERFACE;
909 
910     private static final String CAR_SERVICE_PACKAGE = "com.android.car";
911 
912     private static final String CAR_SERVICE_CLASS = "com.android.car.CarService";
913 
914     /**
915      * Category used by navigation applications to indicate which activity should be launched on
916      * the instrument cluster when such application holds
917      * {@link CarAppFocusManager#APP_FOCUS_TYPE_NAVIGATION} focus.
918      *
919      * @hide
920      */
921     public static final String CAR_CATEGORY_NAVIGATION = "android.car.cluster.NAVIGATION";
922 
923     /**
924      * When an activity is launched in the cluster, it will receive {@link ClusterActivityState} in
925      * the intent's extra under this key, containing instrument cluster information such as
926      * unobscured area, visibility, etc.
927      *
928      * @hide
929      */
930     @SystemApi
931     public static final String CAR_EXTRA_CLUSTER_ACTIVITY_STATE =
932             "android.car.cluster.ClusterActivityState";
933 
934 
935     /**
936      * Callback to notify the Lifecycle of car service.
937      *
938      * <p>Access to car service should happen
939      * after {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} call with
940      * {@code ready} set {@code true}.</p>
941      *
942      * <p>When {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} is
943      * called with ready set to false, access to car service should stop until car service is ready
944      * again from {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} call
945      * with {@code ready} set to {@code true}.</p>
946      */
947     public interface CarServiceLifecycleListener {
948         /**
949          * Car service has gone through status change.
950          *
951          * <p>This is always called in the main thread context.</p>
952          *
953          * @param car {@code Car} object that was originally associated with this lister from
954          *            {@link #createCar(Context, Handler, long, Car.CarServiceLifecycleListener)}
955          *            call.
956          * @param ready When {@code true, car service is ready and all accesses are ok.
957          *              Otherwise car service has crashed or killed and will be restarted.
958          */
onLifecycleChanged(@onNull Car car, boolean ready)959         void onLifecycleChanged(@NonNull Car car, boolean ready);
960     }
961 
962     /**
963      * {@link #createCar(Context, Handler, long, CarServiceLifecycleListener)}'s
964      * waitTimeoutMs value to use to wait forever inside the call until car service is ready.
965      */
966     public static final long CAR_WAIT_TIMEOUT_WAIT_FOREVER = -1;
967 
968     /**
969      * {@link #createCar(Context, Handler, long, CarServiceLifecycleListener)}'s
970      * waitTimeoutMs value to use to skip any waiting inside the call.
971      */
972     public static final long CAR_WAIT_TIMEOUT_DO_NOT_WAIT = 0;
973 
974     private static final long CAR_SERVICE_BIND_RETRY_INTERVAL_MS = 500;
975     private static final long CAR_SERVICE_BIND_MAX_RETRY = 20;
976 
977     private static final long CAR_SERVICE_BINDER_POLLING_INTERVAL_MS = 50;
978     private static final long CAR_SERVICE_BINDER_POLLING_MAX_RETRY = 100;
979 
980     private static final int STATE_DISCONNECTED = 0;
981     private static final int STATE_CONNECTING = 1;
982     private static final int STATE_CONNECTED = 2;
983 
984     /** @hide */
985     @Retention(RetentionPolicy.SOURCE)
986     @IntDef(prefix = "STATE_", value = {
987             STATE_DISCONNECTED,
988             STATE_CONNECTING,
989             STATE_CONNECTED,
990     })
991     @Target({ElementType.TYPE_USE})
992     public @interface StateTypeEnum {}
993 
994     /**
995      * The enabling request was successful and requires reboot to take effect.
996      * @hide
997      */
998     @SystemApi
999     public static final int FEATURE_REQUEST_SUCCESS = 0;
1000     /**
1001      * The requested feature is already enabled or disabled as requested. No need to reboot the
1002      * system.
1003      * @hide
1004      */
1005     @SystemApi
1006     public static final int FEATURE_REQUEST_ALREADY_IN_THE_STATE = 1;
1007     /**
1008      * The requested feature is mandatory cannot be enabled or disabled. It is always enabled.
1009      * @hide
1010      */
1011     @SystemApi
1012     public static final int FEATURE_REQUEST_MANDATORY = 2;
1013     /**
1014      * The requested feature is not available and cannot be enabled or disabled.
1015      * @hide
1016      */
1017     @SystemApi
1018     public static final int FEATURE_REQUEST_NOT_EXISTING = 3;
1019 
1020     /** @hide */
1021     @Retention(RetentionPolicy.SOURCE)
1022     @IntDef(prefix = "FEATURE_REQUEST_", value = {
1023             FEATURE_REQUEST_SUCCESS,
1024             FEATURE_REQUEST_ALREADY_IN_THE_STATE,
1025             FEATURE_REQUEST_MANDATORY,
1026             FEATURE_REQUEST_NOT_EXISTING,
1027     })
1028     @Target({ElementType.TYPE_USE})
1029     public @interface FeaturerRequestEnum {}
1030 
1031     private static final boolean DBG = false;
1032 
1033     private final Context mContext;
1034 
1035     private final Exception mConstructionStack;
1036 
1037     private final Object mLock = new Object();
1038 
1039     @GuardedBy("mLock")
1040     private ICar mService;
1041     @GuardedBy("mLock")
1042     private boolean mServiceBound;
1043 
1044     @GuardedBy("mLock")
1045     @StateTypeEnum
1046     private int mConnectionState;
1047     @GuardedBy("mLock")
1048     private int mConnectionRetryCount;
1049 
1050     private final Runnable mConnectionRetryRunnable = new Runnable() {
1051         @Override
1052         public void run() {
1053             startCarService();
1054         }
1055     };
1056 
1057     private final Runnable mConnectionRetryFailedRunnable = new Runnable() {
1058         @Override
1059         public void run() {
1060             mServiceConnectionListener.onServiceDisconnected(new ComponentName(CAR_SERVICE_PACKAGE,
1061                     CAR_SERVICE_CLASS));
1062         }
1063     };
1064 
1065     private final ServiceConnection mServiceConnectionListener =
1066             new ServiceConnection() {
1067         @Override
1068         public void onServiceConnected(ComponentName name, IBinder service) {
1069             synchronized (mLock) {
1070                 ICar newService = ICar.Stub.asInterface(service);
1071                 if (newService == null) {
1072                     Log.wtf(TAG_CAR, "null binder service", new RuntimeException());
1073                     return;  // should not happen.
1074                 }
1075                 if (mService != null && mService.asBinder().equals(newService.asBinder())) {
1076                     // already connected.
1077                     return;
1078                 }
1079                 mConnectionState = STATE_CONNECTED;
1080                 mService = newService;
1081             }
1082             if (mStatusChangeCallback != null) {
1083                 mStatusChangeCallback.onLifecycleChanged(Car.this, true);
1084             } else if (mServiceConnectionListenerClient != null) {
1085                 mServiceConnectionListenerClient.onServiceConnected(name, service);
1086             }
1087         }
1088 
1089         @Override
1090         public void onServiceDisconnected(ComponentName name) {
1091             // Car service can pick up feature changes after restart.
1092             mFeatures.resetCache();
1093             synchronized (mLock) {
1094                 if (mConnectionState  == STATE_DISCONNECTED) {
1095                     // can happen when client calls disconnect before onServiceDisconnected call.
1096                     return;
1097                 }
1098                 handleCarDisconnectLocked();
1099             }
1100             if (mStatusChangeCallback != null) {
1101                 mStatusChangeCallback.onLifecycleChanged(Car.this, false);
1102             } else if (mServiceConnectionListenerClient != null) {
1103                 mServiceConnectionListenerClient.onServiceDisconnected(name);
1104             } else {
1105                 // This client does not handle car service restart, so should be terminated.
1106                 finishClient();
1107             }
1108         }
1109     };
1110 
1111     @Nullable
1112     private final ServiceConnection mServiceConnectionListenerClient;
1113 
1114     /** Can be added after ServiceManager.getService call */
1115     @Nullable
1116     private final CarServiceLifecycleListener mStatusChangeCallback;
1117 
1118     @GuardedBy("mLock")
1119     private final HashMap<String, CarManagerBase> mServiceMap = new HashMap<>();
1120 
1121     /** Handler for generic event dispatching. */
1122     private final Handler mEventHandler;
1123 
1124     private final Handler mMainThreadEventHandler;
1125 
1126     private final CarFeatures mFeatures = new CarFeatures();
1127 
1128     /**
1129      * A factory method that creates Car instance for all Car API access.
1130      *
1131      * <p>Instance created with this should be disconnected from car service by calling
1132      * {@link #disconnect()} before the passed {code Context} is released.
1133      *
1134      * @param context App's Context. This should not be null. If you are passing
1135      *                {@link ContextWrapper}, make sure that its base Context is non-null as well.
1136      *                Otherwise it will throw {@link java.lang.NullPointerException}.
1137      * @param serviceConnectionListener listener for monitoring service connection.
1138      * @param handler the handler on which the callback should execute, or null to execute on the
1139      * service's main thread. Note: the service connection listener will be always on the main
1140      * thread regardless of the handler given.
1141      * @return Car instance if system is in car environment and returns {@code null} otherwise.
1142      *
1143      * @deprecated use {@link #createCar(Context, Handler)} instead.
1144      */
1145     @Deprecated
createCar(Context context, ServiceConnection serviceConnectionListener, @Nullable Handler handler)1146     public static Car createCar(Context context, ServiceConnection serviceConnectionListener,
1147             @Nullable Handler handler) {
1148         assertNonNullContext(context);
1149         if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
1150             Log.e(TAG_CAR, "FEATURE_AUTOMOTIVE not declared while android.car is used");
1151             return null;
1152         }
1153         try {
1154             return new Car(context, /* service= */ null , serviceConnectionListener,
1155                     /* statusChangeListener= */ null, handler);
1156         } catch (IllegalArgumentException e) {
1157             // Expected when car service loader is not available.
1158         }
1159         return null;
1160     }
1161 
1162     /**
1163      * A factory method that creates Car instance for all Car API access using main thread {@code
1164      * Looper}.
1165      *
1166      * <p>Instance created with this should be disconnected from car service by calling
1167      * {@link #disconnect()} before the passed {code Context} is released.
1168      *
1169      * @see #createCar(Context, ServiceConnection, Handler)
1170      *
1171      * @deprecated use {@link #createCar(Context, Handler)} instead.
1172      */
1173     @Deprecated
createCar(Context context, ServiceConnection serviceConnectionListener)1174     public static Car createCar(Context context, ServiceConnection serviceConnectionListener) {
1175         return createCar(context, serviceConnectionListener, null);
1176     }
1177 
1178     /**
1179      * Creates new {@link Car} object which connected synchronously to Car Service and ready to use.
1180      *
1181      * <p>Instance created with this should be disconnected from car service by calling
1182      * {@link #disconnect()} before the passed {code Context} is released.
1183      *
1184      * @param context application's context
1185      *
1186      * @return Car object if operation succeeded, otherwise null.
1187      */
1188     @Nullable
createCar(Context context)1189     public static Car createCar(Context context) {
1190         return createCar(context, (Handler) null);
1191     }
1192 
1193     /**
1194      * Creates new {@link Car} object which connected synchronously to Car Service and ready to use.
1195      *
1196      * <p>Instance created with this should be disconnected from car service by calling
1197      * {@link #disconnect()} before the passed {code Context} is released.
1198      *
1199      * @param context App's Context. This should not be null. If you are passing
1200      *                {@link ContextWrapper}, make sure that its base Context is non-null as well.
1201      *                Otherwise it will throw {@link java.lang.NullPointerException}.
1202      * @param handler the handler on which the manager's callbacks will be executed, or null to
1203      * execute on the application's main thread.
1204      *
1205      * @return Car object if operation succeeded, otherwise null.
1206      */
1207     @Nullable
createCar(Context context, @Nullable Handler handler)1208     public static Car createCar(Context context, @Nullable Handler handler) {
1209         assertNonNullContext(context);
1210         Car car = null;
1211         IBinder service = null;
1212         boolean started = false;
1213         int retryCount = 0;
1214         while (true) {
1215             service = ServiceManager.getService(CAR_SERVICE_BINDER_SERVICE_NAME);
1216             if (car == null) {
1217                 // service can be still null. The constructor is safe for null service.
1218                 car = new Car(context, ICar.Stub.asInterface(service),
1219                         null /*serviceConnectionListener*/, null /*statusChangeListener*/, handler);
1220             }
1221             if (service != null) {
1222                 if (!started) {  // specialization for most common case.
1223                     // Do this to crash client when car service crashes.
1224                     car.startCarService();
1225                     return car;
1226                 }
1227                 break;
1228             }
1229             if (!started) {
1230                 car.startCarService();
1231                 started = true;
1232             }
1233             retryCount++;
1234             if (retryCount > CAR_SERVICE_BINDER_POLLING_MAX_RETRY) {
1235                 Log.e(TAG_CAR, "cannot get car_service, waited for car service (ms):"
1236                                 + CAR_SERVICE_BINDER_POLLING_INTERVAL_MS
1237                                 * CAR_SERVICE_BINDER_POLLING_MAX_RETRY,
1238                         new RuntimeException());
1239                 return null;
1240             }
1241             try {
1242                 Thread.sleep(CAR_SERVICE_BINDER_POLLING_INTERVAL_MS);
1243             } catch (InterruptedException e) {
1244                 Log.e(CarLibLog.TAG_CAR, "interrupted while waiting for car_service",
1245                         new RuntimeException());
1246                 return null;
1247             }
1248         }
1249         // Can be accessed from mServiceConnectionListener in main thread.
1250         synchronized (car) {
1251             if (car.mService == null) {
1252                 car.mService = ICar.Stub.asInterface(service);
1253                 Log.w(TAG_CAR,
1254                         "waited for car_service (ms):"
1255                                 + CAR_SERVICE_BINDER_POLLING_INTERVAL_MS * retryCount,
1256                         new RuntimeException());
1257             }
1258             car.mConnectionState = STATE_CONNECTED;
1259         }
1260         return car;
1261     }
1262 
1263     /**
1264      * Creates new {@link Car} object with {@link CarServiceLifecycleListener}.
1265      *
1266      * <p>Instance created with this should be disconnected from car service by calling
1267      * {@link #disconnect()} before the passed {code Context} is released.
1268      *
1269      * <p> If car service is ready inside this call and if the caller is running in the main thread,
1270      * {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} will be called
1271      * with ready set to be true. Otherwise,
1272      * {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} will be called
1273      * from the main thread later. </p>
1274      *
1275      * <p>This call can block up to specified waitTimeoutMs to wait for car service to be ready.
1276      * If car service is not ready within the given time, it will return a Car instance in
1277      * disconnected state. Blocking main thread forever can lead into getting ANR (Application Not
1278      * Responding) killing from system and should not be used if the app is supposed to survive
1279      * across the crash / restart of car service. It can be still useful in case the app cannot do
1280      * anything without car service being ready. In any waiting, if the thread is getting
1281      * interrupted, it will return immediately.
1282      * </p>
1283      *
1284      * <p>Note that returned {@link Car} object is not guaranteed to be connected when there is
1285      * a limited timeout. Regardless of returned car being connected or not, it is recommended to
1286      * implement all car related initialization inside
1287      * {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} and avoid the
1288      * needs to check if returned {@link Car} is connected or not from returned {@link Car}.</p>
1289      *
1290      * @param context App's Context. This should not be null. If you are passing
1291      *                {@link ContextWrapper}, make sure that its base Context is non-null as well.
1292      *                Otherwise it will throw {@link java.lang.NullPointerException}.
1293      * @param handler dispatches all Car*Manager events to this Handler. Exception is
1294      *                {@link CarServiceLifecycleListener} which will be always dispatched to main
1295      *                thread. Passing null leads into dispatching all Car*Manager callbacks to main
1296      *                thread as well.
1297      * @param waitTimeoutMs Setting this to {@link #CAR_WAIT_TIMEOUT_DO_NOT_WAIT} will guarantee
1298      *                      that the API does not wait for the car service at all. Setting this to
1299      *                      to {@link #CAR_WAIT_TIMEOUT_WAIT_FOREVER} will block the call forever
1300      *                      until the car service is ready. Setting any positive value will be
1301      *                      interpreted as timeout value.
1302      */
1303     @NonNull
createCar(@onNull Context context, @Nullable Handler handler, long waitTimeoutMs, @NonNull CarServiceLifecycleListener statusChangeListener)1304     public static Car createCar(@NonNull Context context,
1305             @Nullable Handler handler, long waitTimeoutMs,
1306             @NonNull CarServiceLifecycleListener statusChangeListener) {
1307         assertNonNullContext(context);
1308         Objects.requireNonNull(statusChangeListener);
1309         Car car = null;
1310         IBinder service = null;
1311         boolean started = false;
1312         int retryCount = 0;
1313         long maxRetryCount = 0;
1314         if (waitTimeoutMs > 0) {
1315             maxRetryCount = waitTimeoutMs / CAR_SERVICE_BINDER_POLLING_INTERVAL_MS;
1316             // at least wait once if it is positive value.
1317             if (maxRetryCount == 0) {
1318                 maxRetryCount = 1;
1319             }
1320         }
1321         boolean isMainThread = Looper.myLooper() == Looper.getMainLooper();
1322         while (true) {
1323             service = ServiceManager.getService(CAR_SERVICE_BINDER_SERVICE_NAME);
1324             if (car == null) {
1325                 // service can be still null. The constructor is safe for null service.
1326                 car = new Car(context, ICar.Stub.asInterface(service), null, statusChangeListener,
1327                         handler);
1328             }
1329             if (service != null) {
1330                 if (!started) {  // specialization for most common case : car service already ready
1331                     car.dispatchCarReadyToMainThread(isMainThread);
1332                     // Needs this for CarServiceLifecycleListener. Note that ServiceConnection
1333                     // will skip the callback as valid mService is set already.
1334                     car.startCarService();
1335                     return car;
1336                 }
1337                 // service available after starting.
1338                 break;
1339             }
1340             if (!started) {
1341                 car.startCarService();
1342                 started = true;
1343             }
1344             retryCount++;
1345             if (waitTimeoutMs < 0 && retryCount >= CAR_SERVICE_BINDER_POLLING_MAX_RETRY
1346                     && retryCount % CAR_SERVICE_BINDER_POLLING_MAX_RETRY == 0) {
1347                 // Log warning if car service is not alive even for waiting forever case.
1348                 Log.w(TAG_CAR, "car_service not ready, waited for car service (ms):"
1349                                 + retryCount * CAR_SERVICE_BINDER_POLLING_INTERVAL_MS,
1350                         new RuntimeException());
1351             } else if (waitTimeoutMs >= 0 && retryCount > maxRetryCount) {
1352                 if (waitTimeoutMs > 0) {
1353                     Log.w(TAG_CAR, "car_service not ready, waited for car service (ms):"
1354                                     + waitTimeoutMs,
1355                             new RuntimeException());
1356                 }
1357                 return car;
1358             }
1359 
1360             try {
1361                 Thread.sleep(CAR_SERVICE_BINDER_POLLING_INTERVAL_MS);
1362             } catch (InterruptedException e) {
1363                 Thread.currentThread().interrupt();
1364                 Log.w(TAG_CAR, "interrupted", new RuntimeException());
1365                 return car;
1366             }
1367         }
1368         // Can be accessed from mServiceConnectionListener in main thread.
1369         synchronized (car.mLock) {
1370             Log.w(TAG_CAR,
1371                     "waited for car_service (ms):"
1372                             + retryCount * CAR_SERVICE_BINDER_POLLING_INTERVAL_MS,
1373                     new RuntimeException());
1374             // ServiceConnection has handled everything.
1375             if (car.mService != null) {
1376                 return car;
1377             }
1378             // mService check in ServiceConnection prevents calling
1379             // onLifecycleChanged. So onLifecycleChanged should be called explicitly
1380             // but do it outside lock.
1381             car.mService = ICar.Stub.asInterface(service);
1382             car.mConnectionState = STATE_CONNECTED;
1383         }
1384         car.dispatchCarReadyToMainThread(isMainThread);
1385         return car;
1386     }
1387 
assertNonNullContext(Context context)1388     private static void assertNonNullContext(Context context) {
1389         Objects.requireNonNull(context);
1390         if (context instanceof ContextWrapper
1391                 && ((ContextWrapper) context).getBaseContext() == null) {
1392             throw new NullPointerException(
1393                     "ContextWrapper with null base passed as Context, forgot to set base Context?");
1394         }
1395     }
1396 
dispatchCarReadyToMainThread(boolean isMainThread)1397     private void dispatchCarReadyToMainThread(boolean isMainThread) {
1398         if (isMainThread) {
1399             mStatusChangeCallback.onLifecycleChanged(this, true);
1400         } else {
1401             // should dispatch to main thread.
1402             mMainThreadEventHandler.post(
1403                     () -> mStatusChangeCallback.onLifecycleChanged(this, true));
1404         }
1405     }
1406 
Car(Context context, @Nullable ICar service, @Nullable ServiceConnection serviceConnectionListener, @Nullable CarServiceLifecycleListener statusChangeListener, @Nullable Handler handler)1407     private Car(Context context, @Nullable ICar service,
1408             @Nullable ServiceConnection serviceConnectionListener,
1409             @Nullable CarServiceLifecycleListener statusChangeListener,
1410             @Nullable Handler handler) {
1411         mContext = context;
1412         mEventHandler = determineEventHandler(handler);
1413         mMainThreadEventHandler = determineMainThreadEventHandler(mEventHandler);
1414 
1415         mService = service;
1416         if (service != null) {
1417             mConnectionState = STATE_CONNECTED;
1418         } else {
1419             mConnectionState = STATE_DISCONNECTED;
1420         }
1421         mServiceConnectionListenerClient = serviceConnectionListener;
1422         mStatusChangeCallback = statusChangeListener;
1423         // Store construction stack so that client can get help when it crashes when car service
1424         // crashes.
1425         if (serviceConnectionListener == null && statusChangeListener == null) {
1426             mConstructionStack = new RuntimeException();
1427         } else {
1428             mConstructionStack = null;
1429         }
1430     }
1431 
1432     /**
1433      * Car constructor when ICar binder is already available. The binder can be null.
1434      * @hide
1435      */
Car(Context context, @Nullable ICar service, @Nullable Handler handler)1436     public Car(Context context, @Nullable ICar service, @Nullable Handler handler) {
1437         this(context, service, null /*serviceConnectionListener*/, null /*statusChangeListener*/,
1438                 handler);
1439     }
1440 
determineMainThreadEventHandler(Handler eventHandler)1441     private static Handler determineMainThreadEventHandler(Handler eventHandler) {
1442         Looper mainLooper = Looper.getMainLooper();
1443         return (eventHandler.getLooper() == mainLooper) ? eventHandler : new Handler(mainLooper);
1444     }
1445 
determineEventHandler(@ullable Handler handler)1446     private static Handler determineEventHandler(@Nullable Handler handler) {
1447         if (handler == null) {
1448             Looper looper = Looper.getMainLooper();
1449             handler = new Handler(looper);
1450         }
1451         return handler;
1452     }
1453 
1454     /**
1455      * Connect to car service. This can be called while it is disconnected.
1456      * @throws IllegalStateException If connection is still on-going from previous
1457      *         connect call or it is already connected
1458      *
1459      * @deprecated this method is not need if this object is created via
1460      * {@link #createCar(Context, Handler)}.
1461      */
1462     @Deprecated
connect()1463     public void connect() throws IllegalStateException {
1464         synchronized (mLock) {
1465             if (mConnectionState != STATE_DISCONNECTED) {
1466                 throw new IllegalStateException("already connected or connecting");
1467             }
1468             mConnectionState = STATE_CONNECTING;
1469             startCarService();
1470         }
1471     }
1472 
handleCarDisconnectLocked()1473     private void handleCarDisconnectLocked() {
1474         if (mConnectionState == STATE_DISCONNECTED) {
1475             // can happen when client calls disconnect with onServiceDisconnected already called.
1476             return;
1477         }
1478         mEventHandler.removeCallbacks(mConnectionRetryRunnable);
1479         mMainThreadEventHandler.removeCallbacks(mConnectionRetryFailedRunnable);
1480         mConnectionRetryCount = 0;
1481         tearDownCarManagersLocked();
1482         mService = null;
1483         mConnectionState = STATE_DISCONNECTED;
1484     }
1485 
1486     /**
1487      * Disconnect from car service. This can be called while disconnected. Once disconnect is
1488      * called, all Car*Managers from this instance becomes invalid, and
1489      * {@link Car#getCarManager(String)} will return different instance if it is connected again.
1490      */
disconnect()1491     public void disconnect() {
1492         synchronized (mLock) {
1493             handleCarDisconnectLocked();
1494             if (mServiceBound) {
1495                 mContext.unbindService(mServiceConnectionListener);
1496                 mServiceBound = false;
1497             }
1498         }
1499     }
1500 
1501     /**
1502      * Tells if it is connected to the service or not. This will return false if it is still
1503      * connecting.
1504      * @return
1505      */
isConnected()1506     public boolean isConnected() {
1507         synchronized (mLock) {
1508             return mService != null;
1509         }
1510     }
1511 
1512     /**
1513      * Tells if this instance is already connecting to car service or not.
1514      * @return
1515      */
isConnecting()1516     public boolean isConnecting() {
1517         synchronized (mLock) {
1518             return mConnectionState == STATE_CONNECTING;
1519         }
1520     }
1521 
1522     /** @hide */
1523     @VisibleForTesting
getServiceConnectionListener()1524     public ServiceConnection getServiceConnectionListener() {
1525         return mServiceConnectionListener;
1526     }
1527 
1528     /**
1529      * Get car specific service as in {@link Context#getSystemService(String)}. Returned
1530      * {@link Object} should be type-casted to the desired service.
1531      * For example, to get sensor service,
1532      * SensorManagerService sensorManagerService = car.getCarManager(Car.SENSOR_SERVICE);
1533      * @param serviceName Name of service that should be created like {@link #SENSOR_SERVICE}.
1534      * @return Matching service manager or null if there is no such service.
1535      */
1536     @Nullable
getCarManager(String serviceName)1537     public Object getCarManager(String serviceName) {
1538         CarManagerBase manager;
1539         synchronized (mLock) {
1540             if (mService == null) {
1541                 Log.w(TAG_CAR, "getCarManager not working while car service not ready");
1542                 return null;
1543             }
1544             manager = mServiceMap.get(serviceName);
1545             if (manager == null) {
1546                 try {
1547                     IBinder binder = mService.getCarService(serviceName);
1548                     if (binder == null) {
1549                         Log.w(TAG_CAR, "getCarManager could not get binder for service:"
1550                                 + serviceName);
1551                         return null;
1552                     }
1553                     manager = createCarManagerLocked(serviceName, binder);
1554                     if (manager == null) {
1555                         Log.w(TAG_CAR, "getCarManager could not create manager for service:"
1556                                         + serviceName);
1557                         return null;
1558                     }
1559                     mServiceMap.put(serviceName, manager);
1560                 } catch (RemoteException e) {
1561                     handleRemoteExceptionFromCarService(e);
1562                 }
1563             }
1564         }
1565         return manager;
1566     }
1567 
1568     /**
1569      * @return the type of currently connected car.
1570      *
1571      * @deprecated connection type will be always {@link CONNECTION_TYPE_EMBEDDED}
1572      */
1573     @ConnectionType
1574     @Deprecated
getCarConnectionType()1575     public int getCarConnectionType() {
1576         return CONNECTION_TYPE_EMBEDDED;
1577     }
1578 
1579     /**
1580      * Checks if {code featureName} is enabled in this car.
1581      *
1582      * <p>For optional features, this can return false if the car cannot support it. Optional
1583      * features should be used only when they are supported.</p>
1584      *
1585      * <p>For mandatory features, this will always return true.
1586      */
isFeatureEnabled(@onNull String featureName)1587     public boolean isFeatureEnabled(@NonNull String featureName) {
1588         ICar service;
1589         synchronized (mLock) {
1590             if (mService == null) {
1591                 return false;
1592             }
1593             service = mService;
1594         }
1595         return mFeatures.isFeatureEnabled(service, featureName);
1596     }
1597 
1598     /**
1599      * Enables the requested car feature. It becomes no-op if the feature is already enabled. The
1600      * change take effects after reboot.
1601      *
1602      * @return true if the feature is enabled or was enabled before.
1603      *
1604      * @hide
1605      */
1606     @SystemApi
1607     @RequiresPermission(PERMISSION_CONTROL_CAR_FEATURES)
1608     @FeaturerRequestEnum
enableFeature(@onNull String featureName)1609     public int enableFeature(@NonNull String featureName) {
1610         ICar service;
1611         synchronized (mLock) {
1612             if (mService == null) {
1613                 return FEATURE_REQUEST_NOT_EXISTING;
1614             }
1615             service = mService;
1616         }
1617         try {
1618             return service.enableFeature(featureName);
1619         } catch (RemoteException e) {
1620             return handleRemoteExceptionFromCarService(e, FEATURE_REQUEST_NOT_EXISTING);
1621         }
1622     }
1623 
1624     /**
1625      * Disables the requested car feature. It becomes no-op if the feature is already disabled. The
1626      * change take effects after reboot.
1627      *
1628      * @return true if the request succeeds or if it was already disabled.
1629      *
1630      * @hide
1631      */
1632     @SystemApi
1633     @RequiresPermission(PERMISSION_CONTROL_CAR_FEATURES)
1634     @FeaturerRequestEnum
disableFeature(@onNull String featureName)1635     public int disableFeature(@NonNull String featureName) {
1636         ICar service;
1637         synchronized (mLock) {
1638             if (mService == null) {
1639                 return FEATURE_REQUEST_NOT_EXISTING;
1640             }
1641             service = mService;
1642         }
1643         try {
1644             return service.disableFeature(featureName);
1645         } catch (RemoteException e) {
1646             return handleRemoteExceptionFromCarService(e, FEATURE_REQUEST_NOT_EXISTING);
1647         }
1648     }
1649 
1650     /**
1651      * Returns all =enabled features at the moment including mandatory, optional, and
1652      * experimental features.
1653      *
1654      * @hide
1655      */
1656     @SystemApi
1657     @RequiresPermission(PERMISSION_CONTROL_CAR_FEATURES)
getAllEnabledFeatures()1658     @NonNull public List<String> getAllEnabledFeatures() {
1659         ICar service;
1660         synchronized (mLock) {
1661             if (mService == null) {
1662                 return Collections.EMPTY_LIST;
1663             }
1664             service = mService;
1665         }
1666         try {
1667             return service.getAllEnabledFeatures();
1668         } catch (RemoteException e) {
1669             return handleRemoteExceptionFromCarService(e, Collections.EMPTY_LIST);
1670         }
1671     }
1672 
1673     /**
1674      * Returns the list of disabled features which are not effective yet. Those features will be
1675      * disabled when system restarts later.
1676      *
1677      * @hide
1678      */
1679     @SystemApi
1680     @RequiresPermission(PERMISSION_CONTROL_CAR_FEATURES)
getAllPendingDisabledFeatures()1681     @NonNull public List<String> getAllPendingDisabledFeatures() {
1682         ICar service;
1683         synchronized (mLock) {
1684             if (mService == null) {
1685                 return Collections.EMPTY_LIST;
1686             }
1687             service = mService;
1688         }
1689         try {
1690             return service.getAllPendingDisabledFeatures();
1691         } catch (RemoteException e) {
1692             return handleRemoteExceptionFromCarService(e, Collections.EMPTY_LIST);
1693         }
1694     }
1695 
1696     /**
1697      * Returns the list of enabled features which are not effective yet. Those features will be
1698      * enabled when system restarts later.
1699      *
1700      * @hide
1701      */
1702     @SystemApi
1703     @RequiresPermission(PERMISSION_CONTROL_CAR_FEATURES)
getAllPendingEnabledFeatures()1704     @NonNull public List<String> getAllPendingEnabledFeatures() {
1705         ICar service;
1706         synchronized (mLock) {
1707             if (mService == null) {
1708                 return Collections.EMPTY_LIST;
1709             }
1710             service = mService;
1711         }
1712         try {
1713             return service.getAllPendingEnabledFeatures();
1714         } catch (RemoteException e) {
1715             return handleRemoteExceptionFromCarService(e, Collections.EMPTY_LIST);
1716         }
1717     }
1718 
1719     /** @hide */
getContext()1720     public Context getContext() {
1721         return mContext;
1722     }
1723 
1724     /** @hide */
1725     @VisibleForTesting
getEventHandler()1726     public Handler getEventHandler() {
1727         return mEventHandler;
1728     }
1729 
1730     /** @hide */
1731     @VisibleForTesting
handleRemoteExceptionFromCarService(RemoteException e, T returnValue)1732     public <T> T handleRemoteExceptionFromCarService(RemoteException e, T returnValue) {
1733         handleRemoteExceptionFromCarService(e);
1734         return returnValue;
1735     }
1736 
1737     /** @hide */
handleRemoteExceptionFromCarService(RemoteException e)1738     void handleRemoteExceptionFromCarService(RemoteException e) {
1739         if (e instanceof TransactionTooLargeException) {
1740             Log.w(TAG_CAR, "Car service threw TransactionTooLargeException", e);
1741             throw new CarTransactionException(e, "Car service threw TransactionTooLargException");
1742         } else {
1743             Log.w(TAG_CAR, "Car service has crashed", e);
1744         }
1745     }
1746 
finishClient()1747     private void finishClient() {
1748         if (mContext == null) {
1749             throw new IllegalStateException("Car service has crashed, null Context");
1750         }
1751         if (mContext instanceof Activity) {
1752             Activity activity = (Activity) mContext;
1753             if (!activity.isFinishing()) {
1754                 Log.w(TAG_CAR,
1755                         "Car service crashed, client not handling it, finish Activity, created "
1756                                 + "from " + mConstructionStack);
1757                 activity.finish();
1758             }
1759             return;
1760         } else if (mContext instanceof Service) {
1761             Service service = (Service) mContext;
1762             killClient(service.getPackageName() + "," + service.getClass().getSimpleName());
1763         } else {
1764             killClient(/* clientInfo= */ null);
1765         }
1766     }
1767 
killClient(@ullable String clientInfo)1768     private void killClient(@Nullable String clientInfo) {
1769         Log.w(TAG_CAR, "**Car service has crashed. Client(" + clientInfo + ") is not handling it."
1770                         + " Client should use Car.createCar(..., CarServiceLifecycleListener, .."
1771                         + ".) to handle it properly. Check pritned callstack to check where other "
1772                         + "version of Car.createCar() was called. Killing the client process**",
1773                 mConstructionStack);
1774         Process.killProcess(Process.myPid());
1775     }
1776 
1777     /** @hide */
handleRemoteExceptionFromCarService(Service service, RemoteException e, T returnValue)1778     public static <T> T handleRemoteExceptionFromCarService(Service service, RemoteException e,
1779             T returnValue) {
1780         handleRemoteExceptionFromCarService(service, e);
1781         return returnValue;
1782     }
1783 
1784     /** @hide */
handleRemoteExceptionFromCarService(Service service, RemoteException e)1785     public static  void handleRemoteExceptionFromCarService(Service service, RemoteException e) {
1786         if (e instanceof TransactionTooLargeException) {
1787             Log.w(TAG_CAR, "Car service threw TransactionTooLargeException, client:"
1788                     + service.getPackageName() + ","
1789                     + service.getClass().getSimpleName(), e);
1790             throw new CarTransactionException(e, "Car service threw TransactionTooLargeException, "
1791                 + "client: %s, %s", service.getPackageName(), service.getClass().getSimpleName());
1792         } else {
1793             Log.w(TAG_CAR, "Car service has crashed, client:"
1794                     + service.getPackageName() + ","
1795                     + service.getClass().getSimpleName(), e);
1796             service.stopSelf();
1797         }
1798     }
1799 
1800     @Nullable
createCarManagerLocked(String serviceName, IBinder binder)1801     private CarManagerBase createCarManagerLocked(String serviceName, IBinder binder) {
1802         CarManagerBase manager = null;
1803         switch (serviceName) {
1804             case AUDIO_SERVICE:
1805                 manager = new CarAudioManager(this, binder);
1806                 break;
1807             case SENSOR_SERVICE:
1808                 manager = new CarSensorManager(this, binder);
1809                 break;
1810             case INFO_SERVICE:
1811                 manager = new CarInfoManager(this, binder);
1812                 break;
1813             case APP_FOCUS_SERVICE:
1814                 manager = new CarAppFocusManager(this, binder);
1815                 break;
1816             case PACKAGE_SERVICE:
1817                 manager = new CarPackageManager(this, binder);
1818                 break;
1819             case CAR_OCCUPANT_ZONE_SERVICE:
1820                 manager = new CarOccupantZoneManager(this, binder);
1821                 break;
1822             case CAR_NAVIGATION_SERVICE:
1823                 manager = new CarNavigationStatusManager(this, binder);
1824                 break;
1825             case CABIN_SERVICE:
1826                 manager = new CarCabinManager(this, binder);
1827                 break;
1828             case DIAGNOSTIC_SERVICE:
1829                 manager = new CarDiagnosticManager(this, binder);
1830                 break;
1831             case HVAC_SERVICE:
1832                 manager = new CarHvacManager(this, binder);
1833                 break;
1834             case POWER_SERVICE:
1835                 manager = new CarPowerManager(this, binder);
1836                 break;
1837             case PROJECTION_SERVICE:
1838                 manager = new CarProjectionManager(this, binder);
1839                 break;
1840             case PROPERTY_SERVICE:
1841                 manager = new CarPropertyManager(this, ICarProperty.Stub.asInterface(binder));
1842                 break;
1843             case VENDOR_EXTENSION_SERVICE:
1844                 manager = new CarVendorExtensionManager(this, binder);
1845                 break;
1846             case CAR_INSTRUMENT_CLUSTER_SERVICE:
1847                 manager = new CarInstrumentClusterManager(this, binder);
1848                 break;
1849             case TEST_SERVICE:
1850                 /* CarTestManager exist in static library. So instead of constructing it here,
1851                  * only pass binder wrapper so that CarTestManager can be constructed outside. */
1852                 manager = new CarTestManagerBinderWrapper(this, binder);
1853                 break;
1854             case VEHICLE_MAP_SERVICE:
1855                 manager = new VmsClientManager(this, binder);
1856                 break;
1857             case VMS_SUBSCRIBER_SERVICE:
1858                 manager = VmsSubscriberManager.wrap(this,
1859                         (VmsClientManager) getCarManager(VEHICLE_MAP_SERVICE));
1860                 break;
1861             case BLUETOOTH_SERVICE:
1862                 manager = new CarBluetoothManager(this, binder);
1863                 break;
1864             case STORAGE_MONITORING_SERVICE:
1865                 manager = new CarStorageMonitoringManager(this, binder);
1866                 break;
1867             case CAR_DRIVING_STATE_SERVICE:
1868                 manager = new CarDrivingStateManager(this, binder);
1869                 break;
1870             case CAR_UX_RESTRICTION_SERVICE:
1871                 manager = new CarUxRestrictionsManager(this, binder);
1872                 break;
1873             case OCCUPANT_AWARENESS_SERVICE:
1874                 manager = new OccupantAwarenessManager(this, binder);
1875                 break;
1876             case CAR_MEDIA_SERVICE:
1877                 manager = new CarMediaManager(this, binder);
1878                 break;
1879             case CAR_BUGREPORT_SERVICE:
1880                 manager = new CarBugreportManager(this, binder);
1881                 break;
1882             case CAR_USER_SERVICE:
1883                 manager = new CarUserManager(this, binder);
1884                 break;
1885             case CAR_WATCHDOG_SERVICE:
1886                 manager = new CarWatchdogManager(this, binder);
1887                 break;
1888             case CAR_INPUT_SERVICE:
1889                 manager = new CarInputManager(this, binder);
1890                 break;
1891             case CAR_DEVICE_POLICY_SERVICE:
1892                 manager = new CarDevicePolicyManager(this, binder);
1893                 break;
1894             case CLUSTER_HOME_SERVICE:
1895                 manager = new ClusterHomeManager(this, binder);
1896                 break;
1897             case CAR_EVS_SERVICE:
1898                 manager = new CarEvsManager(this, binder);
1899                 break;
1900             case CAR_TELEMETRY_SERVICE:
1901                 manager = new CarTelemetryManager(this, binder);
1902                 break;
1903             default:
1904                 // Experimental or non-existing
1905                 String className = null;
1906                 try {
1907                     className = mService.getCarManagerClassForFeature(serviceName);
1908                 } catch (RemoteException e) {
1909                     handleRemoteExceptionFromCarService(e);
1910                     return null;
1911                 }
1912                 if (className == null) {
1913                     Log.e(TAG_CAR, "Cannot construct CarManager for service:" + serviceName
1914                             + " : no class defined");
1915                     return null;
1916                 }
1917                 manager = constructCarManager(className, binder);
1918                 break;
1919         }
1920         return manager;
1921     }
1922 
constructCarManager(String className, IBinder binder)1923     private CarManagerBase constructCarManager(String className, IBinder binder) {
1924         try {
1925             // Should use class loader for the Context as class loader for car api does not
1926             // see the class.
1927             ClassLoader loader = mContext.getClassLoader();
1928             Class managerClass = loader.loadClass(className);
1929             Constructor constructor = managerClass.getConstructor(Car.class, IBinder.class);
1930             CarManagerBase manager = (CarManagerBase) constructor.newInstance(this, binder);
1931             return manager;
1932         } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException
1933                 | InstantiationException | InvocationTargetException e) {
1934             Log.e(TAG_CAR, "Cannot construct CarManager, class:" + className, e);
1935             return null;
1936         }
1937     }
1938 
startCarService()1939     private void startCarService() {
1940         Intent intent = new Intent();
1941         intent.setPackage(CAR_SERVICE_PACKAGE);
1942         intent.setAction(Car.CAR_SERVICE_INTERFACE_NAME);
1943         boolean bound = mContext.bindServiceAsUser(intent, mServiceConnectionListener,
1944                 Context.BIND_AUTO_CREATE, UserHandle.CURRENT_OR_SELF);
1945         synchronized (mLock) {
1946             if (!bound) {
1947                 mConnectionRetryCount++;
1948                 if (mConnectionRetryCount > CAR_SERVICE_BIND_MAX_RETRY) {
1949                     Log.w(TAG_CAR, "cannot bind to car service after max retry");
1950                     mMainThreadEventHandler.post(mConnectionRetryFailedRunnable);
1951                 } else {
1952                     mEventHandler.postDelayed(mConnectionRetryRunnable,
1953                             CAR_SERVICE_BIND_RETRY_INTERVAL_MS);
1954                 }
1955             } else {
1956                 mEventHandler.removeCallbacks(mConnectionRetryRunnable);
1957                 mMainThreadEventHandler.removeCallbacks(mConnectionRetryFailedRunnable);
1958                 mConnectionRetryCount = 0;
1959                 mServiceBound = true;
1960             }
1961         }
1962     }
1963 
tearDownCarManagersLocked()1964     private void tearDownCarManagersLocked() {
1965         // All disconnected handling should be only doing its internal cleanup.
1966         for (CarManagerBase manager: mServiceMap.values()) {
1967             manager.onCarDisconnected();
1968         }
1969         mServiceMap.clear();
1970     }
1971 }
1972