• 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 import static android.car.feature.Flags.FLAG_ANDROID_B_VEHICLE_PROPERTIES;
21 import static android.car.feature.Flags.FLAG_CLUSTER_HEALTH_MONITORING;
22 import static android.car.feature.Flags.FLAG_VEHICLE_PROPERTY_25Q2_3P_PERMISSIONS;
23 import static android.car.feature.Flags.FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS;
24 
25 import android.annotation.FlaggedApi;
26 import android.annotation.IntDef;
27 import android.annotation.NonNull;
28 import android.annotation.Nullable;
29 import android.annotation.RequiresPermission;
30 import android.annotation.SdkConstant;
31 import android.annotation.SdkConstant.SdkConstantType;
32 import android.annotation.SuppressLint;
33 import android.annotation.SystemApi;
34 import android.annotation.TestApi;
35 import android.app.Activity;
36 import android.app.Service;
37 import android.car.admin.CarDevicePolicyManager;
38 import android.car.annotation.MandatoryFeature;
39 import android.car.annotation.OptionalFeature;
40 import android.car.app.CarActivityManager;
41 import android.car.app.CarDisplayCompatManager;
42 import android.car.builtin.os.BuildHelper;
43 import android.car.builtin.os.ServiceManagerHelper;
44 import android.car.builtin.util.Slogf;
45 import android.car.cluster.CarInstrumentClusterManager;
46 import android.car.cluster.ClusterActivityState;
47 import android.car.cluster.ClusterHomeManager;
48 import android.car.content.pm.CarPackageManager;
49 import android.car.diagnostic.CarDiagnosticManager;
50 import android.car.drivingstate.CarDrivingStateManager;
51 import android.car.drivingstate.CarUxRestrictionsManager;
52 import android.car.evs.CarEvsManager;
53 import android.car.feature.Flags;
54 import android.car.hardware.CarSensorManager;
55 import android.car.hardware.CarVendorExtensionManager;
56 import android.car.hardware.cabin.CarCabinManager;
57 import android.car.hardware.hvac.CarHvacManager;
58 import android.car.hardware.power.CarPowerManager;
59 import android.car.hardware.property.CarPropertyManager;
60 import android.car.hardware.property.CarPropertySimulationManager;
61 import android.car.hardware.property.ICarProperty;
62 import android.car.input.CarInputManager;
63 import android.car.media.CarAudioManager;
64 import android.car.media.CarMediaIntents;
65 import android.car.media.CarMediaManager;
66 import android.car.navigation.CarNavigationStatusManager;
67 import android.car.occupantawareness.OccupantAwarenessManager;
68 import android.car.occupantconnection.CarOccupantConnectionManager;
69 import android.car.os.CarPerformanceManager;
70 import android.car.remoteaccess.CarRemoteAccessManager;
71 import android.car.storagemonitoring.CarStorageMonitoringManager;
72 import android.car.telemetry.CarTelemetryManager;
73 import android.car.test.CarTestManager;
74 import android.car.user.CarUserManager;
75 import android.car.vms.VmsClientManager;
76 import android.car.vms.VmsSubscriberManager;
77 import android.car.watchdog.CarWatchdogManager;
78 import android.car.wifi.CarWifiManager;
79 import android.content.ComponentName;
80 import android.content.Context;
81 import android.content.ContextWrapper;
82 import android.content.Intent;
83 import android.content.ServiceConnection;
84 import android.content.pm.PackageManager;
85 import android.os.Build;
86 import android.os.Handler;
87 import android.os.IBinder;
88 import android.os.Looper;
89 import android.os.RemoteException;
90 import android.os.SystemClock;
91 import android.os.TransactionTooLargeException;
92 import android.util.ArrayMap;
93 import android.util.Slog;
94 
95 import com.android.car.internal.ICarBase;
96 import com.android.car.internal.VisibleForHiddenApiCheck;
97 import com.android.car.internal.common.CommonConstants;
98 import com.android.car.internal.dep.SystemProperties;
99 import com.android.car.internal.os.Process;
100 import com.android.car.internal.os.ServiceManager;
101 import com.android.car.internal.os.SystemProcess;
102 import com.android.car.internal.os.SystemServiceManager;
103 import com.android.internal.annotations.GuardedBy;
104 import com.android.internal.annotations.VisibleForTesting;
105 
106 import java.lang.annotation.ElementType;
107 import java.lang.annotation.Retention;
108 import java.lang.annotation.RetentionPolicy;
109 import java.lang.annotation.Target;
110 import java.lang.reflect.Constructor;
111 import java.lang.reflect.InvocationTargetException;
112 import java.util.Collections;
113 import java.util.HashMap;
114 import java.util.List;
115 import java.util.Map;
116 import java.util.Objects;
117 
118 /**
119  *   Top level car API for Android Automotive OS deployments.
120  *   This API works only for devices with {@link PackageManager#FEATURE_AUTOMOTIVE}
121  *   Calling this API on a device with no such feature will lead to an exception.
122  */
123 public final class Car implements ICarBase {
124 
125     /**
126      * System property to define platform minor version.
127      *
128      * <p>Value is int string. Check {@link #PROPERTY_PLATFORM_MINOR_INT} for further details.
129      * If not set, default value of {@code 0} is assumed.
130      */
131     private static final String PROPERTY_PLATFORM_MINOR_VERSION =
132             "ro.android.car.version.platform_minor";
133 
134     /**
135      * @deprecated - This does not return the correct version. Use
136      * {@code getCarVersion().getMajorVersion()} instead.
137      */
138     @Deprecated
139     public static final int API_VERSION_MAJOR_INT = 34;
140 
141     /**
142      * @deprecated - This does not return the correct version. Use
143      * {@code getCarVersion().getMinorVersion()} instead
144      */
145     @Deprecated
146     public static final int API_VERSION_MINOR_INT = 0;
147 
148 
149     /**
150      * @deprecated - use {@code getPlatformApiVersion().getMinorVersion()} instead
151      */
152     @Deprecated
153     public static final int PLATFORM_VERSION_MINOR_INT = SystemProperties
154             .getInt(PROPERTY_PLATFORM_MINOR_VERSION, /* def= */ 0);
155 
156     // These are the actual car api versions. Due to legacy reasons, we cannot modfiy
157     // API_VERSION_MAJOR_INT and API_VERSION_MINOR_INT because they were exposed as public.
158     private static final int ACTUAL_API_VERSION_MAJOR_INT = Build.VERSION.SDK_INT;
159     private static final int ACTUAL_API_VERSION_MINOR_INT = 0;
160 
161     private static final CarVersion CAR_VERSION = CarVersion.newInstance("Car.CAR_VERSION",
162             ACTUAL_API_VERSION_MAJOR_INT, ACTUAL_API_VERSION_MINOR_INT);
163 
164     private static final PlatformVersion PLATFORM_VERSION;
165 
166     /**
167      * @hide
168      */
169     @TestApi
170     public static final String PROPERTY_EMULATED_PLATFORM_VERSION_MAJOR =
171             "com.android.car.internal.debug.platform_major_version";
172     /**
173      * @hide
174      */
175     @TestApi
176     public static final String PROPERTY_EMULATED_PLATFORM_VERSION_MINOR =
177             "com.android.car.internal.debug.platform_minor_version";
178 
179     static {
180         PlatformVersion emulated = null;
181         if (!BuildHelper.isUserBuild()) {
182             int major = SystemProperties.getInt(PROPERTY_EMULATED_PLATFORM_VERSION_MAJOR, -1);
183             if (major != -1) {
184                 int minor = SystemProperties.getInt(PROPERTY_EMULATED_PLATFORM_VERSION_MINOR,
185                         PLATFORM_VERSION_MINOR_INT);
186                 emulated = android.car.PlatformVersion.newInstance("EMULATED", major, minor);
Slog.i(TAG_CAR, "Emulating PLATFORM_VERSION version: " + emulated)187                 Slog.i(TAG_CAR, "Emulating PLATFORM_VERSION version: " + emulated);
188             }
189         }
190         PLATFORM_VERSION =
191                 emulated != null ? emulated : PlatformVersion.getCurrentPlatformVersionForMinor(
192                         "Car.PLATFORM_VERSION", PLATFORM_VERSION_MINOR_INT);
193     }
194 
195     // Car service registry information.
196     // This information never changes after the static initialization completes.
197     private static final Map<Class<?>, String> CAR_SERVICE_NAMES =
198             new ArrayMap<Class<?>, String>(39);
199 
200     /**
201      * Binder service name of car service registered to service manager.
202      *
203      * @hide
204      */
205     @VisibleForHiddenApiCheck
206     public static final String CAR_SERVICE_BINDER_SERVICE_NAME = "car_service";
207 
208     /**
209      * This represents AndroidManifest meta-data to tell that {@code Activity} is optimized for
210      * driving distraction.
211      *
212      * <p>Activities without this meta-data can be blocked while car is in moving / driving state.
213      *
214      * <p>Note that having this flag does not guarantee that the {@code Activity} will be always
215      * allowed for all driving states.
216      *
217      * <p>For this meta-data, android:value can be {@code true} (=optimized) or {@code false}.
218      *
219      * <p>Example usage:
220      * <xml><meta-data android:name="distractionOptimized" android:value="true"/></xml>
221      */
222     @SuppressLint("IntentName")
223     public static final String META_DATA_DISTRACTION_OPTIMIZED = "distractionOptimized";
224 
225     /**
226      * This represents AndroidManifest meta-data to tell that {@code Application} requires specific
227      * car features to work.
228      *
229      * <p>Apps like launcher or installer app can use this information to filter out apps
230      * not usable in a specific car. This meta-data is not necessary for mandatory features.
231      *
232      * <p>For this meta-data, android:value should contain the feature name string defined by
233      * {@code OptionalFeature} or {@code ExperimentalFeature} annotations.
234      *
235      * <p>Example usage:
236      * <xml><meta-data android:name="requires-car-feature" android:value="diagnostic"/></xml>
237      */
238     @SuppressLint("IntentName")
239     public static final String META_DATA_REQUIRES_CAR_FEATURE = "requires-car-feature";
240 
241     /**
242      * Service name for {@link CarSensorManager}, to be used in {@link #getCarManager(String)}.
243      *
244      * @deprecated  {@link CarSensorManager} is deprecated. Use {@link CarPropertyManager} instead.
245      */
246     @MandatoryFeature
247     @Deprecated
248     public static final String SENSOR_SERVICE = "sensor";
249 
250     /** Service name for {@link CarInfoManager}, to be used in {@link #getCarManager(String)}. */
251     @MandatoryFeature
252     public static final String INFO_SERVICE = "info";
253 
254     /** Service name for {@link CarAppFocusManager}. */
255     @MandatoryFeature
256     public static final String APP_FOCUS_SERVICE = "app_focus";
257 
258     /** Service name for {@link CarPackageManager} */
259     @MandatoryFeature
260     public static final String PACKAGE_SERVICE = "package";
261 
262     /** Service name for {@link CarAudioManager} */
263     @MandatoryFeature
264     public static final String AUDIO_SERVICE = "audio";
265 
266     /** Service name for {@code CarNavigationStatusManager} */
267     @OptionalFeature
268     public static final String CAR_NAVIGATION_SERVICE = "car_navigation_service";
269 
270     /**
271      * Service name for {@link CarOccupantConnectionManager}.
272      *
273      * @hide
274      */
275     @OptionalFeature
276     @SystemApi
277     public static final String CAR_OCCUPANT_CONNECTION_SERVICE = "car_occupant_connection_service";
278 
279     /**
280      * Service name for {@link CarRemoteDeviceManager}.
281      *
282      * @hide
283      */
284     @OptionalFeature
285     @SystemApi
286     public static final String CAR_REMOTE_DEVICE_SERVICE = "car_remote_device_service";
287 
288     /** Service name for {@link CarOccupantZoneManager} */
289     @MandatoryFeature
290     public static final String CAR_OCCUPANT_ZONE_SERVICE = "car_occupant_zone_service";
291 
292     /**
293      * Service name for {@link CarUserManager}
294      *
295      * @hide
296      */
297     @MandatoryFeature
298     @SystemApi
299     public static final String CAR_USER_SERVICE = "car_user_service";
300 
301     /**
302      * Service name for ExperimentalCarKeyguardService
303      *
304      * @hide
305      */
306     @OptionalFeature
307     public static final String EXPERIMENTAL_CAR_KEYGUARD_SERVICE =
308             "experimental_car_keyguard_service";
309 
310     /**
311      * Service name for {@link CarDevicePolicyManager}
312      *
313      * @hide
314      */
315     @MandatoryFeature
316     @SystemApi
317     public static final String CAR_DEVICE_POLICY_SERVICE = "car_device_policy_service";
318 
319     /**
320      * Service name for {@link CarInstrumentClusterManager}
321      *
322      * @deprecated CarInstrumentClusterManager is being deprecated
323      * @hide
324      */
325     @OptionalFeature
326     @Deprecated
327     public static final String CAR_INSTRUMENT_CLUSTER_SERVICE = "cluster_service";
328 
329     /**
330      * Service name for {@link CarCabinManager}.
331      *
332      * @deprecated {@link CarCabinManager} is deprecated. Use {@link CarPropertyManager} instead.
333      * @hide
334      */
335     @MandatoryFeature
336     @Deprecated
337     @SystemApi
338     public static final String CABIN_SERVICE = "cabin";
339 
340     /**
341      * Service name for {@link android.car.diagnostic.CarDiagnosticManager}.
342      * @hide
343      */
344     @OptionalFeature
345     @SystemApi
346     public static final String DIAGNOSTIC_SERVICE = "diagnostic";
347 
348     /**
349      * Service name for {@link CarHvacManager}
350      * @deprecated {@link CarHvacManager} is deprecated. Use {@link CarPropertyManager} instead.
351      * @hide
352      */
353     @MandatoryFeature
354     @Deprecated
355     @SystemApi
356     public static final String HVAC_SERVICE = "hvac";
357 
358     /**
359      * Service name for {@link CarPowerManager}
360      */
361     @MandatoryFeature
362     public static final String POWER_SERVICE = "power";
363 
364     /**
365      * Service name for {@link android.car.CarProjectionManager}
366      * @hide
367      */
368     @MandatoryFeature
369     @SystemApi
370     public static final String PROJECTION_SERVICE = "projection";
371 
372     /**
373      * Service name for {@link CarPropertyManager}
374      */
375     @MandatoryFeature
376     public static final String PROPERTY_SERVICE = "property";
377 
378     /**
379      * Service name for {@link CarVendorExtensionManager}
380      *
381      * @deprecated {@link CarVendorExtensionManager} is deprecated.
382      * Use {@link CarPropertyManager} instead.
383      * @hide
384      */
385     @MandatoryFeature
386     @Deprecated
387     @SystemApi
388     public static final String VENDOR_EXTENSION_SERVICE = "vendor_extension";
389 
390     /**
391      * Service name for {@link VmsClientManager}
392      *
393      * @hide
394      */
395     @OptionalFeature
396     @SystemApi
397     public static final String VEHICLE_MAP_SERVICE = "vehicle_map_service";
398 
399     /**
400      * Service name for {@link VmsSubscriberManager}
401      *
402      * @deprecated {@link VmsSubscriberManager} is deprecated. Use {@link VmsClientManager} instead.
403      * @hide
404      */
405     @OptionalFeature
406     @Deprecated
407     @SystemApi
408     public static final String VMS_SUBSCRIBER_SERVICE = "vehicle_map_subscriber_service";
409 
410     /**
411      * Service name for {@link CarDrivingStateManager}
412      * @hide
413      */
414     @MandatoryFeature
415     @SystemApi
416     public static final String CAR_DRIVING_STATE_SERVICE = "drivingstate";
417 
418     /**
419      * Service name for {@link CarUxRestrictionsManager}
420      */
421     public static final String CAR_UX_RESTRICTION_SERVICE = "uxrestriction";
422 
423     /**
424      * Service name for {@link android.car.occupantawareness.OccupantAwarenessManager}
425      * @hide
426      */
427     @OptionalFeature
428     @SystemApi
429     public static final String OCCUPANT_AWARENESS_SERVICE = "occupant_awareness";
430 
431     /**
432      * Service name for {@link android.car.media.CarMediaManager}
433      * @hide
434      */
435     @MandatoryFeature
436     @SystemApi
437     public static final String CAR_MEDIA_SERVICE = "car_media";
438 
439     /**
440      * Service name for {@link android.car.CarBugreportManager}
441      * @hide
442      */
443     @MandatoryFeature
444     @SystemApi
445     public static final String CAR_BUGREPORT_SERVICE = "car_bugreport";
446 
447     /**
448      * Service name for {@link android.car.storagemonitoring.CarStorageMonitoringManager}
449      * @hide
450      */
451     @OptionalFeature
452     @SystemApi
453     public static final String STORAGE_MONITORING_SERVICE = "storage_monitoring";
454 
455     /**
456      * Service name for {@link android.car.watchdog.CarWatchdogManager}
457      */
458     @MandatoryFeature
459     public static final String CAR_WATCHDOG_SERVICE = "car_watchdog";
460 
461     /**
462      * Service name for {@link android.car.os.CarPerformanceManager}
463      *
464      * @hide
465      */
466     @MandatoryFeature
467     @SystemApi
468     public static final String CAR_PERFORMANCE_SERVICE = "car_performance";
469 
470     /**
471      * Service name for {@link android.car.input.CarInputManager}
472      * @hide
473      */
474     @MandatoryFeature
475     @SystemApi
476     public static final String CAR_INPUT_SERVICE = "android.car.input";
477 
478     /**
479      * Service name for {@link android.car.cluster.ClusterHomeManager}
480      * @hide
481      */
482     @OptionalFeature
483     public static final String CLUSTER_HOME_SERVICE = "cluster_home_service";
484 
485     /**
486      * Service for testing. This is system app only feature.
487      * Service name for {@link CarTestManager}, to be used in {@link #getCarManager(String)}.
488      * @hide
489      */
490     @MandatoryFeature
491     @SystemApi
492     public static final String TEST_SERVICE = "car-service-test";
493 
494     /**
495      * Service name for {@link android.car.evs.CarEvsManager}
496      *
497      * @hide
498      */
499     @OptionalFeature
500     @SystemApi
501     public static final String CAR_EVS_SERVICE = "car_evs_service";
502 
503     /**
504      * Service name for {@link android.car.telemetry.CarTelemetryManager}
505      *
506      * @hide
507      */
508     @OptionalFeature
509     @SystemApi
510     public static final String CAR_TELEMETRY_SERVICE = "car_telemetry_service";
511 
512     /**
513      * Service name for {@link android.car.app.CarActivityManager}
514      *
515      * @hide
516      */
517     @MandatoryFeature
518     @SystemApi
519     public static final String CAR_ACTIVITY_SERVICE = "car_activity_service";
520 
521     /**
522      * Service name for {@link android.car.remoteaccess.CarRemoteAccessManager}
523      *
524      * @hide
525      */
526     @OptionalFeature
527     @SystemApi
528     public static final String CAR_REMOTE_ACCESS_SERVICE = "car_remote_access_service";
529 
530     /**
531      * Service name for {@link android.car.wifi.CarWifiManager}
532      *
533      * @hide
534      */
535     @MandatoryFeature
536     @SystemApi
537     @FlaggedApi(Flags.FLAG_PERSIST_AP_SETTINGS)
538     public static final String CAR_WIFI_SERVICE = "car_wifi_service";
539 
540     /**
541      * Signature|Privileged permission necessary to read driver monitoring systems settings
542      * information.
543      *
544      * Examples of settings include the ENABLED properties for the supported driver monitoring
545      * features.
546      */
547     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
548     public static final String PERMISSION_READ_DRIVER_MONITORING_SETTINGS =
549             "android.car.permission.READ_DRIVER_MONITORING_SETTINGS";
550 
551     /**
552      * Signature|Privileged permission necessary to control driver monitoring systems settings
553      * information.
554      *
555      * Examples of settings include the ENABLED properties for the supported driver monitoring
556      * features.
557      */
558     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
559     public static final String PERMISSION_CONTROL_DRIVER_MONITORING_SETTINGS =
560             "android.car.permission.CONTROL_DRIVER_MONITORING_SETTINGS";
561 
562     /**
563      * Signature|Privileged permission necessary to read driver monitoring systems states
564      * information.
565      *
566      * Examples of states include the STATE and WARNING properties for the supported driver
567      * monitoring features.
568      *
569      * This is different from {@link PERMISSION_READ_DRIVER_MONITORING_SETTINGS}, which allows an
570      * app to read the system settings, such as whether the system is enabled or disabled.
571      */
572     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
573     public static final String PERMISSION_READ_DRIVER_MONITORING_STATES =
574             "android.car.permission.READ_DRIVER_MONITORING_STATES";
575 
576     /**
577      * Signature|Privileged permission necessary to access car's mileage information.
578      */
579     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
580     public static final String PERMISSION_MILEAGE = "android.car.permission.CAR_MILEAGE";
581 
582     /**
583      * Dangerous permission necessary to access car's mileage information.
584      */
585     @FlaggedApi(FLAG_ANDROID_B_VEHICLE_PROPERTIES)
586     public static final String PERMISSION_MILEAGE_3P = "android.car.permission.CAR_MILEAGE_3P";
587 
588     /**
589      * Dangerous permission necessary to access car's energy information.
590      */
591     public static final String PERMISSION_ENERGY = "android.car.permission.CAR_ENERGY";
592 
593     /**
594      * Signature|Privileged permission necessary to control car's EV charge settings.
595      */
596     public static final String PERMISSION_CONTROL_CAR_ENERGY =
597             "android.car.permission.CONTROL_CAR_ENERGY";
598 
599     /**
600      * Signature|Privileged permission necessary to change value of car's range remaining.
601      */
602     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
603     public static final String PERMISSION_ADJUST_RANGE_REMAINING =
604             "android.car.permission.ADJUST_RANGE_REMAINING";
605 
606     /**
607      * Signature|Privileged permission necessary to access car's VIN information
608      */
609     public static final String PERMISSION_IDENTIFICATION =
610             "android.car.permission.CAR_IDENTIFICATION";
611 
612     /**
613      * Dangerous permission necessary to access car's speed.
614      */
615     public static final String PERMISSION_SPEED = "android.car.permission.CAR_SPEED";
616 
617     /**
618      * Signature|Privileged permission necessary to access car's dynamics state.
619      */
620     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
621     public static final String PERMISSION_CAR_DYNAMICS_STATE =
622             "android.car.permission.CAR_DYNAMICS_STATE";
623 
624     /**
625      * Signature|Privileged permission necessary to control car's dynamics state.
626      */
627     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
628     public static final String PERMISSION_CONTROL_CAR_DYNAMICS_STATE =
629             "android.car.permission.CONTROL_CAR_DYNAMICS_STATE";
630 
631     /**
632      * Normal permission necessary to access car's fuel door and ev charge port.
633      */
634     public static final String PERMISSION_ENERGY_PORTS = "android.car.permission.CAR_ENERGY_PORTS";
635 
636     /**
637      * Signature|Privileged permission necessary to control car's fuel door and ev charge port.
638      */
639     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
640     public static final String PERMISSION_CONTROL_ENERGY_PORTS =
641             "android.car.permission.CONTROL_CAR_ENERGY_PORTS";
642 
643     /**
644      * Signature|Privileged permission necessary to read car's exterior lights information.
645      */
646     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
647     public static final String PERMISSION_EXTERIOR_LIGHTS =
648             "android.car.permission.CAR_EXTERIOR_LIGHTS";
649 
650     /**
651      * Dangerous permission necessary to read car's exterior lights information.
652      */
653     @FlaggedApi(FLAG_ANDROID_B_VEHICLE_PROPERTIES)
654     public static final String PERMISSION_READ_EXTERIOR_LIGHTS =
655             "android.car.permission.READ_CAR_EXTERIOR_LIGHTS";
656 
657     /**
658      * Signature|Privileged permission necessary to read car's interior lights information.
659      */
660     public static final String PERMISSION_READ_INTERIOR_LIGHTS =
661             "android.car.permission.READ_CAR_INTERIOR_LIGHTS";
662 
663     /**
664      * Signature|Privileged permission necessary to control car's exterior lights.
665      */
666     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
667     public static final String PERMISSION_CONTROL_EXTERIOR_LIGHTS =
668             "android.car.permission.CONTROL_CAR_EXTERIOR_LIGHTS";
669 
670     /**
671      * Dangerous permission necessary to read car horn state.
672      */
673     @FlaggedApi(FLAG_ANDROID_B_VEHICLE_PROPERTIES)
674     public static final String PERMISSION_READ_CAR_HORN = "android.car.permission.READ_CAR_HORN";
675 
676     /**
677      * Signature|Privileged permission necessary to control car horn state.
678      */
679     @FlaggedApi(FLAG_ANDROID_B_VEHICLE_PROPERTIES)
680     public static final String PERMISSION_CONTROL_CAR_HORN =
681             "android.car.permission.CONTROL_CAR_HORN";
682 
683     /**
684      * Dangerous permission necessary to read car pedal information.
685      */
686     @FlaggedApi(FLAG_ANDROID_B_VEHICLE_PROPERTIES)
687     public static final String PERMISSION_READ_CAR_PEDALS =
688             "android.car.permission.READ_CAR_PEDALS";
689 
690     /**
691      * Dangerous permission necessary to read brake information.
692      */
693     @FlaggedApi(FLAG_ANDROID_B_VEHICLE_PROPERTIES)
694     public static final String PERMISSION_READ_BRAKE_INFO =
695             "android.car.permission.READ_BRAKE_INFO";
696 
697     /**
698      * Signature|Privileged permission necessary to control car's interior lights.
699      */
700     public static final String PERMISSION_CONTROL_INTERIOR_LIGHTS =
701             "android.car.permission.CONTROL_CAR_INTERIOR_LIGHTS";
702 
703     /**
704      * Normal permission necessary to access car's powertrain information.
705      */
706     public static final String PERMISSION_POWERTRAIN = "android.car.permission.CAR_POWERTRAIN";
707 
708     /**
709      * Signature|Privileged permission necessary to control car's powertrain information.
710      */
711     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
712     public static final String PERMISSION_CONTROL_POWERTRAIN =
713             "android.car.permission.CONTROL_CAR_POWERTRAIN";
714 
715     /**
716      * Signature|Privileged permission necessary to change car audio volume through
717      * {@link CarAudioManager}.
718      */
719     public static final String PERMISSION_CAR_CONTROL_AUDIO_VOLUME =
720             "android.car.permission.CAR_CONTROL_AUDIO_VOLUME";
721 
722     /**
723      * Signature|Privileged permission necessary to change car audio settings through
724      * {@link CarAudioManager}.
725      */
726     public static final String PERMISSION_CAR_CONTROL_AUDIO_SETTINGS =
727             "android.car.permission.CAR_CONTROL_AUDIO_SETTINGS";
728 
729     /**
730      * Signature|Privileged permission necessary to receive full audio ducking events from car audio
731      * focus handler.
732      *
733      * @hide
734      */
735     @SystemApi
736     public static final String PERMISSION_RECEIVE_CAR_AUDIO_DUCKING_EVENTS =
737             "android.car.permission.RECEIVE_CAR_AUDIO_DUCKING_EVENTS";
738 
739     /**
740      * Signature|Privileged permission necessary to use {@code CarNavigationStatusManager}.
741      */
742     public static final String PERMISSION_CAR_NAVIGATION_MANAGER =
743             "android.car.permission.CAR_NAVIGATION_MANAGER";
744 
745     /**
746      * Signature|Privileged permission necessary to start activities in the instrument cluster
747      * through {@link CarInstrumentClusterManager}
748      *
749      * @hide
750      */
751     @SystemApi
752     public static final String PERMISSION_CAR_INSTRUMENT_CLUSTER_CONTROL =
753             "android.car.permission.CAR_INSTRUMENT_CLUSTER_CONTROL";
754 
755     /**
756      * Signature|Privileged permission necessary to listen for the instrument cluster's navigation
757      * state changes.
758      *
759      * @hide
760      */
761     @FlaggedApi(FLAG_CLUSTER_HEALTH_MONITORING)
762     @SystemApi
763     public static final String PERMISSION_CAR_MONITOR_CLUSTER_NAVIGATION_STATE =
764             "android.car.permission.CAR_MONITOR_CLUSTER_NAVIGATION_STATE";
765 
766     /**
767      * Signature|Privileged permission required by applications in order to be launched in the
768      * instrument cluster display.
769      *
770      * @hide
771      */
772     @VisibleForHiddenApiCheck
773     public static final String PERMISSION_CAR_DISPLAY_IN_CLUSTER =
774             "android.car.permission.CAR_DISPLAY_IN_CLUSTER";
775 
776     /**
777      * Normal permission necessary to use {@link CarInfoManager}.
778      */
779     public static final String PERMISSION_CAR_INFO = "android.car.permission.CAR_INFO";
780 
781     /**
782      * Signature|Privileged permission necessary to access privileged car info.
783      */
784     public static final String PERMISSION_PRIVILEGED_CAR_INFO =
785             "android.car.permission.PRIVILEGED_CAR_INFO";
786 
787     /**
788      * Signature|Privileged permission necessary to read information of vendor properties'
789      * permissions.
790      * @hide
791      */
792     @SystemApi
793     public static final String PERMISSION_READ_CAR_VENDOR_PERMISSION_INFO =
794             "android.car.permission.READ_CAR_VENDOR_PERMISSION_INFO";
795 
796     /**
797      * Normal permission necessary to read temperature of car's exterior environment.
798      */
799     public static final String PERMISSION_EXTERIOR_ENVIRONMENT =
800             "android.car.permission.CAR_EXTERIOR_ENVIRONMENT";
801 
802     /**
803      * Signature|Privileged permission necessary to access car specific communication channel.
804      * @hide
805      */
806     @SystemApi
807     public static final String PERMISSION_VENDOR_EXTENSION =
808             "android.car.permission.CAR_VENDOR_EXTENSION";
809 
810     /**
811      * Signature|Privileged permission.
812      * @hide
813      */
814     @SystemApi
815     public static final String PERMISSION_CONTROL_APP_BLOCKING =
816             "android.car.permission.CONTROL_APP_BLOCKING";
817 
818     /**
819      * Signature|Privileged permission necessary to access car's engine information.
820      */
821     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
822     public static final String PERMISSION_CAR_ENGINE_DETAILED =
823             "android.car.permission.CAR_ENGINE_DETAILED";
824 
825     /**
826      * Dangerous permission necessary to access car's engine information.
827      */
828     @FlaggedApi(FLAG_VEHICLE_PROPERTY_25Q2_3P_PERMISSIONS)
829     public static final String PERMISSION_CAR_ENGINE_DETAILED_3P =
830             "android.car.permission.CAR_ENGINE_DETAILED_3P";
831 
832     /**
833      * Signature|Privileged permission necessary to access car's tire pressure information.
834      */
835     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
836     public static final String PERMISSION_TIRES = "android.car.permission.CAR_TIRES";
837 
838     /**
839      * Dangerous permission necessary to access car's tire pressure information.
840      */
841     @FlaggedApi(FLAG_VEHICLE_PROPERTY_25Q2_3P_PERMISSIONS)
842     public static final String PERMISSION_TIRES_3P = "android.car.permission.CAR_TIRES_3P";
843 
844     /**
845      * Signature|Privileged permission necessary to access car's property
846      * {@link VehiclePropertyIds#EPOCH_TIME}.
847      */
848     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
849     public static final String PERMISSION_CAR_EPOCH_TIME = "android.car.permission.CAR_EPOCH_TIME";
850 
851     /**
852      * Signature|Privileged permission necessary to access car's steering angle information.
853      */
854     public static final String PERMISSION_READ_STEERING_STATE =
855             "android.car.permission.READ_CAR_STEERING";
856 
857     /**
858      * Dangerous permission necessary to access car's steering angle information.
859      */
860     @FlaggedApi(FLAG_VEHICLE_PROPERTY_25Q2_3P_PERMISSIONS)
861     public static final String PERMISSION_READ_STEERING_STATE_3P =
862             "android.car.permission.READ_CAR_STEERING_3P";
863 
864     /**
865      * Normal permission necessary to read and write display units for distance, fuel volume,
866      * tire pressure and ev battery.
867      */
868     public static final String PERMISSION_READ_DISPLAY_UNITS =
869             "android.car.permission.READ_CAR_DISPLAY_UNITS";
870 
871     /**
872      * Normal permission necessary to control display units for distance, fuel volume, tire pressure
873      * and ev battery. Currently, all display unit properties require both {@code
874      * PERMISSION_CONTROL_DISPLAY_UNITS} and {@code PERMISSION_VENDOR_EXTENSION} to be granted in
875      * order to write to them.
876      */
877     public static final String PERMISSION_CONTROL_DISPLAY_UNITS =
878             "android.car.permission.CONTROL_CAR_DISPLAY_UNITS";
879 
880     /**
881      * Signature|Privileged permission necessary to control car's door.
882      */
883     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
884     public static final String PERMISSION_CONTROL_CAR_DOORS =
885             "android.car.permission.CONTROL_CAR_DOORS";
886 
887     /**
888      * Signature|Privileged permission necessary to control car's windows.
889      */
890     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
891     public static final String PERMISSION_CONTROL_CAR_WINDOWS =
892             "android.car.permission.CONTROL_CAR_WINDOWS";
893 
894     /**
895      * Signature|Privileged permission necessary to control car glove box.
896      */
897     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
898     public static final String PERMISSION_CONTROL_GLOVE_BOX =
899             "android.car.permission.CONTROL_GLOVE_BOX";
900 
901     /**
902      * Dangerous permission necessary to read car's seats.
903      */
904     @FlaggedApi(FLAG_VEHICLE_PROPERTY_25Q2_3P_PERMISSIONS)
905     public static final String PERMISSION_READ_CAR_SEATS = "android.car.permission.READ_CAR_SEATS";
906 
907     /**
908      * Signature|Privileged permission necessary to control car's seats.
909      */
910     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
911     public static final String PERMISSION_CONTROL_CAR_SEATS =
912             "android.car.permission.CONTROL_CAR_SEATS";
913 
914     /**
915      * Signature|Privileged permission necessary to control car's mirrors.
916      */
917     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
918     public static final String PERMISSION_CONTROL_CAR_MIRRORS =
919             "android.car.permission.CONTROL_CAR_MIRRORS";
920 
921     /**
922      * Signature|Privileged permission necessary to access Car HVAC APIs.
923      */
924     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
925     public static final String PERMISSION_CONTROL_CAR_CLIMATE =
926             "android.car.permission.CONTROL_CAR_CLIMATE";
927 
928     /**
929      * Signature|Privileged permission necessary to enable/disable a seat's ability to deploy
930      * airbag(s) when triggered (e.g. by a crash).
931      */
932     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
933     public static final String PERMISSION_CONTROL_CAR_AIRBAGS =
934             "android.car.permission.CONTROL_CAR_AIRBAGS";
935 
936 
937     /**
938      * Signature|Privileged|VendorPrivileged permission necessary to access restrictive car power
939      * management APIs.
940      * @hide
941      */
942     @SystemApi
943     public static final String PERMISSION_CAR_POWER = "android.car.permission.CAR_POWER";
944 
945     /**
946      * Normal permission necessary to read the current power policy or be notified of power policy
947      * change.
948      */
949     public static final String PERMISSION_READ_CAR_POWER_POLICY =
950             "android.car.permission.READ_CAR_POWER_POLICY";
951 
952     /**
953      * Signature|Privileged|VendorPrivileged permission necessary to apply a new power policy.
954      * @hide
955      */
956     @SystemApi
957     public static final String PERMISSION_CONTROL_CAR_POWER_POLICY =
958             "android.car.permission.CONTROL_CAR_POWER_POLICY";
959 
960     /**
961      * Signature|Privileged|VendorPrivileged permission necessary to adjust the shutdown process.
962      * @hide
963      */
964     @SystemApi
965     public static final String PERMISSION_CONTROL_SHUTDOWN_PROCESS =
966             "android.car.permission.CONTROL_SHUTDOWN_PROCESS";
967 
968     /**
969      * Signature|Privileged permission necessary to access Car PROJECTION system APIs.
970      * @hide
971      */
972     @SystemApi
973     public static final String PERMISSION_CAR_PROJECTION = "android.car.permission.CAR_PROJECTION";
974 
975     /**
976      * Signature|Privileged permission necessary to access projection status.
977      * @hide
978      */
979     @SystemApi
980     public static final String PERMISSION_CAR_PROJECTION_STATUS =
981             "android.car.permission.ACCESS_CAR_PROJECTION_STATUS";
982 
983     /**
984      * Signature|Privileged permission necessary to mock vehicle hal for testing.
985      * @hide
986      * @deprecated mocking vehicle HAL in car service is no longer supported.
987      */
988     @Deprecated
989     @SystemApi
990     public static final String PERMISSION_MOCK_VEHICLE_HAL =
991             "android.car.permission.CAR_MOCK_VEHICLE_HAL";
992 
993     /**
994      * Signature|Privileged permission necessary to access CarTestService.
995      * @hide
996      */
997     @SystemApi
998     public static final String PERMISSION_CAR_TEST_SERVICE =
999             "android.car.permission.CAR_TEST_SERVICE";
1000 
1001     /**
1002      * Signature|Privileged permission necessary to access a car's driving state
1003      * (E.g. CarDrivingStateService).
1004      */
1005     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1006     public static final String PERMISSION_CAR_DRIVING_STATE =
1007             "android.car.permission.CAR_DRIVING_STATE";
1008 
1009     /**
1010      * Dangerous permission necessary to access a car's driving state.
1011      */
1012     @FlaggedApi(FLAG_VEHICLE_PROPERTY_25Q2_3P_PERMISSIONS)
1013     public static final String PERMISSION_CAR_DRIVING_STATE_3P =
1014             "android.car.permission.CAR_DRIVING_STATE_3P";
1015 
1016     /**
1017      * Signature permission necessary to access VMS client service.
1018      *
1019      * @hide
1020      */
1021     @VisibleForHiddenApiCheck
1022     public static final String PERMISSION_BIND_VMS_CLIENT =
1023             "android.car.permission.BIND_VMS_CLIENT";
1024 
1025     /**
1026      * Signature|Privileged permissions necessary to access VMS publisher APIs.
1027      *
1028      * @hide
1029      */
1030     @SystemApi
1031     public static final String PERMISSION_VMS_PUBLISHER = "android.car.permission.VMS_PUBLISHER";
1032 
1033     /**
1034      * Signature|Privileged permissions necessary to access VMS subscriber APIs.
1035      *
1036      * @hide
1037      */
1038     @SystemApi
1039     public static final String PERMISSION_VMS_SUBSCRIBER = "android.car.permission.VMS_SUBSCRIBER";
1040 
1041     /**
1042      * Signature|Privileged permission necessary to read ultrasonics sensor data.
1043      */
1044     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1045     public static final String PERMISSION_READ_ULTRASONICS_SENSOR_DATA =
1046             "android.car.permission.READ_ULTRASONICS_SENSOR_DATA";
1047 
1048     /**
1049      * Signature|Privileged permissions necessary to read diagnostic information, including
1050      * vendor-specific bits.
1051      *
1052      * @hide
1053      */
1054     @SystemApi
1055     public static final String PERMISSION_CAR_DIAGNOSTIC_READ_ALL =
1056             "android.car.permission.CAR_DIAGNOSTICS";
1057 
1058     /**
1059      * Signature|Privileged permissions necessary to clear diagnostic information.
1060      *
1061      * @hide
1062      */
1063     @SystemApi
1064     public static final String PERMISSION_CAR_DIAGNOSTIC_CLEAR =
1065             "android.car.permission.CLEAR_CAR_DIAGNOSTICS";
1066 
1067     /**
1068      * Signature|Privileged permission necessary to configure UX restrictions through
1069      * {@link CarUxRestrictionsManager}.
1070      *
1071      * @hide
1072      */
1073     @VisibleForHiddenApiCheck
1074     @SystemApi
1075     public static final String PERMISSION_CAR_UX_RESTRICTIONS_CONFIGURATION =
1076             "android.car.permission.CAR_UX_RESTRICTIONS_CONFIGURATION";
1077 
1078     /**
1079      * Signature|Privileged permission necessary to listen to occupant awareness state
1080      * {@link OccupantAwarenessManager}.
1081      *
1082      * @hide
1083      */
1084     @SystemApi
1085     public static final String PERMISSION_READ_CAR_OCCUPANT_AWARENESS_STATE =
1086             "android.car.permission.READ_CAR_OCCUPANT_AWARENESS_STATE";
1087 
1088     /**
1089      * Signature|Privileged permission necessary to access private display id.
1090      *
1091      * @hide
1092      */
1093     @SystemApi
1094     public static final String ACCESS_PRIVATE_DISPLAY_ID =
1095             "android.car.permission.ACCESS_PRIVATE_DISPLAY_ID";
1096 
1097     /**
1098      * @deprecated Signature|Privileged permission that is not used by any service.
1099      *
1100      * @hide
1101      */
1102     @SystemApi
1103     public static final String PERMISSION_CONTROL_CAR_OCCUPANT_AWARENESS_SYSTEM =
1104             "android.car.permission.CONTROL_CAR_OCCUPANT_AWARENESS_SYSTEM";
1105 
1106     /**
1107      * Signature|Privileged permissions necessary to clear diagnostic information.
1108      *
1109      * @hide
1110      */
1111     @SystemApi
1112     public static final String PERMISSION_STORAGE_MONITORING =
1113             "android.car.permission.STORAGE_MONITORING";
1114 
1115     /**
1116      * Signature|Privileged permission necessary to dynamically enable / disable optional car
1117      * features.
1118      *
1119      * @hide
1120      */
1121     @SystemApi
1122     public static final String PERMISSION_CONTROL_CAR_FEATURES =
1123             "android.car.permission.CONTROL_CAR_FEATURES";
1124 
1125     /**
1126      * Signature|Privileged permission necessary to be car watchdog clients.
1127      *
1128      * @hide
1129      */
1130     @SystemApi
1131     public static final String PERMISSION_USE_CAR_WATCHDOG =
1132             "android.car.permission.USE_CAR_WATCHDOG";
1133 
1134     /**
1135      * Signature|Privileged permission necessary to monitor Car input events.
1136      *
1137      * @hide
1138      */
1139     @SystemApi
1140     public static final String PERMISSION_CAR_MONITOR_INPUT =
1141             "android.car.permission.CAR_MONITOR_INPUT";
1142 
1143     /**
1144      * Signature|Privileged permission necessary to request CarEvsService to launch the special
1145      * activity to show the camera preview.
1146      *
1147      * @hide
1148      */
1149     @SystemApi
1150     public static final String PERMISSION_REQUEST_CAR_EVS_ACTIVITY =
1151             "android.car.permission.REQUEST_CAR_EVS_ACTIVITY";
1152 
1153     /**
1154      * Signature|Privileged permission necessary to control the special activity to show the camera
1155      * preview.
1156      *
1157      * @hide
1158      */
1159     @SystemApi
1160     public static final String PERMISSION_CONTROL_CAR_EVS_ACTIVITY =
1161             "android.car.permission.CONTROL_CAR_EVS_ACTIVITY";
1162 
1163     /**
1164      * Signature|Privileged permission necessary to use the camera streams via CarEvsService.
1165      *
1166      * @hide
1167      */
1168     @SystemApi
1169     public static final String PERMISSION_USE_CAR_EVS_CAMERA =
1170             "android.car.permission.USE_CAR_EVS_CAMERA";
1171 
1172     /**
1173      * Signature|Privileged permission necessary to monitor the status of CarEvsService.
1174      *
1175      * @hide
1176      */
1177     @SystemApi
1178     public static final String PERMISSION_MONITOR_CAR_EVS_STATUS =
1179             "android.car.permission.MONITOR_CAR_EVS_STATUS";
1180 
1181     /**
1182      * Signature|Privileged permission necessary to use the CarTelemetryService.
1183      *
1184      * @hide
1185      */
1186     @SystemApi
1187     public static final String PERMISSION_USE_CAR_TELEMETRY_SERVICE =
1188             "android.car.permission.USE_CAR_TELEMETRY_SERVICE";
1189 
1190     /**
1191      * Type of car connection: platform runs directly in car.
1192      *
1193      * @deprecated connection type constants are no longer used
1194      */
1195     @Deprecated
1196     public static final int CONNECTION_TYPE_EMBEDDED = 5;
1197 
1198     /**
1199      * Signature|Privileged permission necessary to be able to render template-based UI metadata on
1200      * behalf of another application.
1201      *
1202      * @hide
1203      */
1204     @SystemApi
1205     public static final String PERMISSION_TEMPLATE_RENDERER =
1206             "android.car.permission.TEMPLATE_RENDERER";
1207 
1208     /**
1209      * Signature|Privileged permission necessary to set or retrieve car watchdog configurations.
1210      *
1211      * @hide
1212      */
1213     @SystemApi
1214     public static final String PERMISSION_CONTROL_CAR_WATCHDOG_CONFIG =
1215             "android.car.permission.CONTROL_CAR_WATCHDOG_CONFIG";
1216 
1217     /**
1218      * Signature|Privileged permission necessary to collect metrics from car watchdog.
1219      *
1220      * @hide
1221      */
1222     @SystemApi
1223     public static final String PERMISSION_COLLECT_CAR_WATCHDOG_METRICS =
1224             "android.car.permission.COLLECT_CAR_WATCHDOG_METRICS";
1225 
1226     /**
1227      * Permission necessary to fetch car CPU information.
1228      *
1229      * @hide
1230      */
1231     public static final String PERMISSION_COLLECT_CAR_CPU_INFO =
1232             "android.car.permission.COLLECT_CAR_CPU_INFO";
1233 
1234     /**
1235      * Signature|Privileged permission necessary to control launching applications in Car.
1236      *
1237      * @hide
1238      */
1239     @SystemApi
1240     public static final String PERMISSION_CONTROL_CAR_APP_LAUNCH =
1241             "android.car.permission.CONTROL_CAR_APP_LAUNCH";
1242 
1243     /**
1244      * Signature|Privileged permission necessary to setting and getting thread scheduling policy and
1245      * priority.
1246      *
1247      * @hide
1248      */
1249     @SystemApi
1250     public static final String PERMISSION_MANAGE_THREAD_PRIORITY =
1251             "android.car.permission.MANAGE_THREAD_PRIORITY";
1252 
1253     /**
1254      * Signature|Privileged permission necessary to modify occupant zone settings. Will be used in
1255      * {@link CarOccupantZoneManager}.
1256      *
1257      * @hide
1258      */
1259     @SystemApi
1260     public static final String PERMISSION_MANAGE_OCCUPANT_ZONE =
1261             "android.car.permission.MANAGE_OCCUPANT_ZONE";
1262 
1263     /**
1264      * Normal permission necessary to use remote access.
1265      */
1266     public static final String PERMISSION_USE_REMOTE_ACCESS =
1267             "android.car.permission.USE_REMOTE_ACCESS";
1268 
1269     /**
1270      * Signature|Privileged permission necessary to control remote access.
1271      *
1272      * @hide
1273      */
1274     @SystemApi
1275     public static final String PERMISSION_CONTROL_REMOTE_ACCESS =
1276             "android.car.permission.CONTROL_REMOTE_ACCESS";
1277     /**
1278      * Signature|Privileged permission necessary to control car's steering wheel.
1279      */
1280     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1281     public static final String PERMISSION_CONTROL_STEERING_WHEEL =
1282             "android.car.permission.CONTROL_STEERING_WHEEL";
1283 
1284     /**
1285      * Signature|Privileged permission necessary to read ADAS settings information.
1286      *
1287      * Examples of settings include the ENABLED properties for the supported ADAS features.
1288      */
1289     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1290     public static final String PERMISSION_READ_ADAS_SETTINGS =
1291             "android.car.permission.READ_ADAS_SETTINGS";
1292 
1293     /**
1294      * Signature|Privileged permission necessary to control ADAS settings information.
1295      *
1296      * Examples of settings include the ENABLED properties for the supported ADAS features.
1297      */
1298     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1299     public static final String PERMISSION_CONTROL_ADAS_SETTINGS =
1300             "android.car.permission.CONTROL_ADAS_SETTINGS";
1301 
1302     /**
1303      * Signature|Privileged permission necessary to read ADAS states information.
1304      *
1305      * Examples include the STATE properties for the supported ADAS features.
1306      */
1307     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1308     public static final String PERMISSION_READ_ADAS_STATES =
1309             "android.car.permission.READ_ADAS_STATES";
1310 
1311     /**
1312      * Signature|Privileged permission necessary to control ADAS states information.
1313      *
1314      * Examples include the STATE properties for the supported ADAS features.
1315      */
1316     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1317     public static final String PERMISSION_CONTROL_ADAS_STATES =
1318             "android.car.permission.CONTROL_ADAS_STATES";
1319 
1320     /**
1321      * Signature|Privileged permission necessary to monitor the states of other occupant zones in
1322      * the car and peer apps (apps that have the same package name as the caller) installed in those
1323      * zones, and manage the power of those zones.
1324      *
1325      * @hide
1326      */
1327     @SystemApi
1328     public static final String PERMISSION_MANAGE_REMOTE_DEVICE =
1329             "android.car.permission.MANAGE_REMOTE_DEVICE";
1330 
1331     /**
1332      * Signature|Privileged permission necessary to establish connection and communicate to peer
1333      * apps (apps that have the same package name as the caller) installed in other occupant zones
1334      * in the car.
1335      *
1336      * @hide
1337      */
1338     @SystemApi
1339     public static final String PERMISSION_MANAGE_OCCUPANT_CONNECTION =
1340             "android.car.permission.MANAGE_OCCUPANT_CONNECTION";
1341 
1342     /**
1343      * Signature|Privileged permission to access the mirrored Surface using the Token generated by
1344      * {@link CarActivityManager#createTaskMirroringToken(int)}.
1345      *
1346      * @hide
1347      */
1348     @SystemApi
1349     public static final String PERMISSION_ACCESS_MIRRORRED_SURFACE =
1350             "android.car.permission.ACCESS_MIRRORED_SURFACE";
1351 
1352     /**
1353      * Signature|Privileged permission to create the mirroring token for the Display.
1354      * See {@link CarActivityManager#createDisplayMirroringToken(int)} (int)}.
1355      *
1356      * @hide
1357      */
1358     @SystemApi
1359     public static final String PERMISSION_MIRROR_DISPLAY =
1360             "android.car.permission.MIRROR_DISPLAY";
1361 
1362     /**
1363      * Signature|Privileged permission necessary to read car's windshield wipers.
1364      */
1365     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1366     public static final String PERMISSION_READ_WINDSHIELD_WIPERS =
1367             "android.car.permission.READ_WINDSHIELD_WIPERS";
1368 
1369     /**
1370      * Dangerous permission necessary to read car's windshield wipers.
1371      */
1372     @FlaggedApi(FLAG_VEHICLE_PROPERTY_25Q2_3P_PERMISSIONS)
1373     public static final String PERMISSION_READ_WINDSHIELD_WIPERS_3P =
1374             "android.car.permission.READ_WINDSHIELD_WIPERS_3P";
1375 
1376     /**
1377      * Signature|Privileged permission necessary to control car's windshield wipers.
1378      */
1379     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1380     public static final String PERMISSION_CONTROL_WINDSHIELD_WIPERS =
1381             "android.car.permission.CONTROL_WINDSHIELD_WIPERS";
1382 
1383     /**
1384      * Signature|Privileged permission necessary to register a {@link SystemUIProxy} that can be
1385      * used by other apps to manage the system ui and create task views.
1386      *
1387      * @hide
1388      */
1389     @SystemApi
1390     public static final String PERMISSION_REGISTER_CAR_SYSTEM_UI_PROXY =
1391             "android.car.permission.REGISTER_CAR_SYSTEM_UI_PROXY";
1392 
1393     /**
1394      * Signature|Privileged permission necessary to communicate with the car system ui for creating
1395      * task views or getting notified about system ui changes.
1396      * @hide
1397      */
1398     @SystemApi
1399     public static final String PERMISSION_MANAGE_CAR_SYSTEM_UI =
1400             "android.car.permission.MANAGE_CAR_SYSTEM_UI";
1401 
1402     /**
1403      * Permission necessary to manage packages that requires launching in automotive compatibility
1404      * mode.
1405      * @hide
1406      */
1407     @FlaggedApi(Flags.FLAG_DISPLAY_COMPATIBILITY)
1408     @SystemApi
1409     public static final String PERMISSION_MANAGE_DISPLAY_COMPATIBILITY =
1410             "android.car.permission.MANAGE_DISPLAY_COMPATIBILITY";
1411 
1412     /**
1413      * Signature|Privileged permission necessary to read state of car airbags.
1414      */
1415     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1416     public static final String PERMISSION_READ_CAR_AIRBAGS =
1417             "android.car.permission.READ_CAR_AIRBAGS";
1418 
1419     /**
1420      * Signature|Privileged permission necessary to read state of seat belts.
1421      */
1422     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1423     public static final String PERMISSION_READ_CAR_SEAT_BELTS =
1424             "android.car.permission.READ_CAR_SEAT_BELTS";
1425 
1426     /**
1427      * Signature|Privileged permission necessary to read impact sensors information.
1428      */
1429     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1430     public static final String PERMISSION_READ_IMPACT_SENSORS =
1431             "android.car.permission.READ_IMPACT_SENSORS";
1432 
1433     /**
1434      * Signature|Privileged permission necessary to read valet mode.
1435      */
1436     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1437     public static final String PERMISSION_READ_VALET_MODE =
1438             "android.car.permission.READ_VALET_MODE";
1439 
1440     /**
1441      * Signature|Privileged permission necessary to control valet mode.
1442      */
1443     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1444     public static final String PERMISSION_CONTROL_VALET_MODE =
1445             "android.car.permission.CONTROL_VALET_MODE";
1446 
1447     /**
1448      * Signature|Privileged permission necessary to read head up display status (e.g. whether the
1449      * head up display is enabled).
1450      */
1451     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1452     public static final String PERMISSION_READ_HEAD_UP_DISPLAY_STATUS =
1453             "android.car.permission.READ_HEAD_UP_DISPLAY_STATUS";
1454 
1455     /**
1456      * Signature|Privileged permission necessary to control head up display.
1457      */
1458     @FlaggedApi(FLAG_VEHICLE_PROPERTY_REMOVE_SYSTEM_API_TAGS)
1459     public static final String PERMISSION_CONTROL_HEAD_UP_DISPLAY =
1460             "android.car.permission.CONTROL_HEAD_UP_DISPLAY";
1461 
1462     /**
1463      * Permission necessary to read persist tethering settings.
1464      * @hide
1465      */
1466     @FlaggedApi(Flags.FLAG_PERSIST_AP_SETTINGS)
1467     @SystemApi
1468     public static final String PERMISSION_READ_PERSIST_TETHERING_SETTINGS =
1469             "android.car.permission.READ_PERSIST_TETHERING_SETTINGS";
1470 
1471     /**
1472      * Permission necessary to bind with app card providers.
1473      * @hide
1474      */
1475     @FlaggedApi(Flags.FLAG_CAR_APP_CARD)
1476     @SystemApi
1477     public static final String PERMISSION_BIND_APP_CARD_PROVIDER =
1478             "android.car.permission.BIND_APP_CARD_PROVIDER";
1479 
1480     /**
1481      * Signature permission necessary to record vehicle properties.
1482      * @hide
1483      */
1484     @FlaggedApi(Flags.FLAG_CAR_PROPERTY_SIMULATION)
1485     @SystemApi
1486     public static final String PERMISSION_RECORD_VEHICLE_PROPERTIES =
1487             "android.car.permission.RECORD_VEHICLE_PROPERTIES";
1488 
1489     /**
1490      * Signature permission necessary to inject vehicle properties for testing purposes.
1491      * @hide
1492      */
1493     @FlaggedApi(Flags.FLAG_CAR_PROPERTY_SIMULATION)
1494     @SystemApi
1495     public static final String PERMISSION_INJECT_VEHICLE_PROPERTIES =
1496             "android.car.permission.INJECT_VEHICLE_PROPERTIES";
1497 
1498     /**
1499      * Intent for connecting to the template renderer. Services that handle this intent must also
1500      * hold {@link #PERMISSION_TEMPLATE_RENDERER}. Applications would not bind to this service
1501      * directly, but instead they would use
1502      * <a href="https://developer.android.com/reference/com/google/android/libraries/car/app/packages">
1503      * Android for Cars App Library</a>.
1504      *
1505      * @hide
1506      */
1507     @SdkConstant(SdkConstantType.SERVICE_ACTION)
1508     public static final String CAR_TEMPLATE_HOST_RENDERER_SERVICE =
1509             "android.car.template.host.RendererService";
1510 
1511     /** @hide */
1512     @IntDef({CONNECTION_TYPE_EMBEDDED})
1513     @Retention(RetentionPolicy.SOURCE)
1514     public @interface ConnectionType {}
1515 
1516     /**
1517      * @deprecated Use {@link CarMediaIntents#ACTION_MEDIA_TEMPLATE} instead.
1518      */
1519     @Deprecated
1520     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1521     public static final String CAR_INTENT_ACTION_MEDIA_TEMPLATE =
1522             "android.car.intent.action.MEDIA_TEMPLATE";
1523 
1524     /**
1525      * @deprecated Use {@link CarMediaIntents#EXTRA_MEDIA_COMPONENT} instead.
1526      */
1527     @Deprecated
1528     public static final String CAR_EXTRA_MEDIA_COMPONENT =
1529             "android.car.intent.extra.MEDIA_COMPONENT";
1530 
1531     /**
1532      *
1533      * @deprecated Use {@link #CAR_EXTRA_MEDIA_COMPONENT} instead.
1534      * @removed Using this for specifying MediaBrowserService was not supported since API level 29
1535      * and above. Apps must use {@link #CAR_EXTRA_MEDIA_COMPONENT} instead.
1536      */
1537     @Deprecated
1538     public static final String CAR_EXTRA_MEDIA_PACKAGE = "android.car.intent.extra.MEDIA_PACKAGE";
1539 
1540     /**
1541      * Used as a string extra field of media session to specify the service corresponding to the
1542      * session.
1543      */
1544     public static final String CAR_EXTRA_BROWSE_SERVICE_FOR_SESSION =
1545             "android.media.session.BROWSE_SERVICE";
1546 
1547     /**
1548      * Intent for being recognized as a remote task client service.
1549      *
1550      * <p>Services that use this intent must have a {@code PERMISSION_CONTROL_REMOTE_ACCESS}.
1551      *
1552      * @hide
1553      */
1554     @SystemApi
1555     public static final String CAR_REMOTEACCESS_REMOTE_TASK_CLIENT_SERVICE =
1556             "android.car.remoteaccess.RemoteTaskClientService";
1557 
1558     /**
1559      * Intent for binding the implementation of {@link
1560      * android.car.occupantconnection.AbstractReceiverService} in the app.
1561      *
1562      * @hide
1563      */
1564     @SdkConstant(SdkConstantType.SERVICE_ACTION)
1565     public static final String CAR_INTENT_ACTION_RECEIVER_SERVICE =
1566             "android.car.intent.action.RECEIVER_SERVICE";
1567 
1568     /** @hide */
1569     @VisibleForHiddenApiCheck
1570     public static final String CAR_SERVICE_INTERFACE_NAME = CommonConstants.CAR_SERVICE_INTERFACE;
1571 
1572     private static final String CAR_SERVICE_PACKAGE = "com.android.car";
1573 
1574     private static final String CAR_SERVICE_CLASS = "com.android.car.CarService";
1575 
1576     /**
1577      * Category used by navigation applications to indicate which activity should be launched on
1578      * the instrument cluster when such application holds
1579      * {@link CarAppFocusManager#APP_FOCUS_TYPE_NAVIGATION} focus.
1580      *
1581      * @hide
1582      */
1583     @VisibleForHiddenApiCheck
1584     public static final String CAR_CATEGORY_NAVIGATION = "android.car.cluster.NAVIGATION";
1585 
1586     /**
1587      * When an activity is launched in the cluster, it will receive {@link ClusterActivityState} in
1588      * the intent's extra under this key, containing instrument cluster information such as
1589      * unobscured area, visibility, etc.
1590      *
1591      * @hide
1592      */
1593     @SystemApi
1594     public static final String CAR_EXTRA_CLUSTER_ACTIVITY_STATE =
1595             "android.car.cluster.ClusterActivityState";
1596 
1597     /**
1598      * @hide
1599      */
1600     @OptionalFeature
1601     @FlaggedApi(Flags.FLAG_DISPLAY_COMPATIBILITY)
1602     @SystemApi
1603     public static final String CAR_DISPLAY_COMPAT_SERVICE = "car_display_compat_service";
1604 
1605     /**
1606      * Service name for {@link android.car.hardware.property.CarPropertySimulationManager}
1607      * @hide
1608      */
1609     @FlaggedApi(Flags.FLAG_CAR_PROPERTY_SIMULATION)
1610     @SystemApi
1611     public static final String CAR_PROPERTY_SIMULATION_SERVICE = "car_property_simulation_service";
1612 
1613     /**
1614      * Callback to notify the Lifecycle of car service.
1615      *
1616      * <p>Access to car service should happen
1617      * after {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} call with
1618      * {@code ready} set {@code true}.</p>
1619      *
1620      * <p>When {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} is
1621      * called with ready set to false, access to car service should stop until car service is ready
1622      * again from {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} call
1623      * with {@code ready} set to {@code true}.</p>
1624      */
1625     public interface CarServiceLifecycleListener {
1626         /**
1627          * Car service has gone through status change.
1628          *
1629          * <p>This is always called in the main thread context.</p>
1630          *
1631          * @param car {@code Car} object that was originally associated with this lister from
1632          *            {@link #createCar(Context, Handler, long, Car.CarServiceLifecycleListener)}
1633          *            call.
1634          * @param ready when {@code true}, car service is ready and all accesses are ok
1635          *              Otherwise car service has crashed or killed and will be restarted
1636          */
onLifecycleChanged(@onNull Car car, boolean ready)1637         void onLifecycleChanged(@NonNull Car car, boolean ready);
1638     }
1639 
1640     /**
1641      * {@link #createCar(Context, Handler, long, CarServiceLifecycleListener)}'s
1642      * waitTimeoutMs value to use to wait forever inside the call until car service is ready.
1643      */
1644     public static final long CAR_WAIT_TIMEOUT_WAIT_FOREVER = -1;
1645 
1646     /**
1647      * {@link #createCar(Context, Handler, long, CarServiceLifecycleListener)}'s
1648      * waitTimeoutMs value to use to skip any waiting inside the call.
1649      */
1650     public static final long CAR_WAIT_TIMEOUT_DO_NOT_WAIT = 0;
1651 
1652     private static final long CAR_SERVICE_BIND_RETRY_INTERVAL_MS = 500;
1653     private static final long CAR_SERVICE_BIND_MAX_RETRY = 20;
1654 
1655     private static final long CAR_SERVICE_BINDER_POLLING_INTERVAL_MS = 50;
1656     private static final long CREATE_CAR_DEFAULT_TIMEOUT_MS = 5_000;
1657 
1658     private static final int STATE_DISCONNECTED = 0;
1659     private static final int STATE_CONNECTING = 1;
1660     private static final int STATE_CONNECTED = 2;
1661 
1662     /** @hide */
1663     @Retention(RetentionPolicy.SOURCE)
1664     @IntDef(prefix = "STATE_", value = {
1665             STATE_DISCONNECTED,
1666             STATE_CONNECTING,
1667             STATE_CONNECTED,
1668     })
1669     @Target({ElementType.TYPE_USE})
1670     public @interface StateTypeEnum {}
1671 
1672     /**
1673      * The enabling request was successful and requires reboot to take effect.
1674      * @hide
1675      */
1676     @SystemApi
1677     public static final int FEATURE_REQUEST_SUCCESS = 0;
1678     /**
1679      * The requested feature is already enabled or disabled as requested. No need to reboot the
1680      * system.
1681      * @hide
1682      */
1683     @SystemApi
1684     public static final int FEATURE_REQUEST_ALREADY_IN_THE_STATE = 1;
1685     /**
1686      * The requested feature is mandatory cannot be enabled or disabled. It is always enabled.
1687      * @hide
1688      */
1689     @SystemApi
1690     public static final int FEATURE_REQUEST_MANDATORY = 2;
1691     /**
1692      * The requested feature is not available and cannot be enabled or disabled.
1693      * @hide
1694      */
1695     @SystemApi
1696     public static final int FEATURE_REQUEST_NOT_EXISTING = 3;
1697 
1698     /** @hide */
1699     @Retention(RetentionPolicy.SOURCE)
1700     @IntDef(prefix = "FEATURE_REQUEST_", value = {
1701             FEATURE_REQUEST_SUCCESS,
1702             FEATURE_REQUEST_ALREADY_IN_THE_STATE,
1703             FEATURE_REQUEST_MANDATORY,
1704             FEATURE_REQUEST_NOT_EXISTING,
1705     })
1706     @Target({ElementType.TYPE_USE})
1707     public @interface FeaturerRequestEnum {}
1708 
1709     private final Context mContext;
1710     private final Exception mConstructionStack;
1711     private final long mCreateUptimeMillis;
1712     private final Object mLock = new Object();
1713 
1714     @GuardedBy("mLock")
1715     private ICar mService;
1716     @GuardedBy("mLock")
1717     private boolean mServiceBound;
1718 
1719     @GuardedBy("mLock")
1720     @StateTypeEnum
1721     private int mConnectionState;
1722     @GuardedBy("mLock")
1723     private int mConnectionRetryCount;
1724 
1725     // Whether we have registered the service listener. It should only be registered once.
1726     @GuardedBy("mLock")
1727     private boolean mServiceListenerRegistered;
1728     // The car service binder object we get from ServiceManager.
1729     @GuardedBy("mLock")
1730     private IBinder mCarServiceBinder;
1731     // Whether the client is currently waiting (blocked) for a car service connection.
1732     @GuardedBy("mLock")
1733     private boolean mWaiting;
1734     // Whether client explicitly called disconnect.
1735     @GuardedBy("mLock")
1736     private boolean mClientRequestDisconnect;
1737 
1738     private final Runnable mConnectionRetryRunnable = new Runnable() {
1739         @Override
1740         public void run() {
1741             startCarService();
1742         }
1743     };
1744 
1745     private final Runnable mConnectionRetryFailedRunnable = new Runnable() {
1746         @Override
1747         public void run() {
1748             mServiceConnectionListener.onServiceDisconnected(new ComponentName(CAR_SERVICE_PACKAGE,
1749                     CAR_SERVICE_CLASS));
1750         }
1751     };
1752 
1753     private final ServiceRegistrationCallbackForCar mServiceRegistrationCallback =
1754              new ServiceRegistrationCallbackForCar();
1755 
1756     private final class ServiceRegistrationCallbackForCar implements
1757             ServiceManagerHelper.IServiceRegistrationCallback  {
1758         @Override
onRegistration(@onNull String name, IBinder binder)1759         public void onRegistration(@NonNull String name, IBinder binder) {
1760             Slog.i(TAG_CAR, "car_service registered");
1761             if (!name.equals(CAR_SERVICE_BINDER_SERVICE_NAME)) {
1762                 Slog.wtf(TAG_CAR, "Unexpected service name called for onRegistration: " + name);
1763                 return;
1764             }
1765             synchronized (mLock) {
1766                 mCarServiceBinder = binder;
1767                 if (mWaiting) {
1768                     mLock.notifyAll();
1769                     return;
1770                 }
1771                 if (mClientRequestDisconnect) {
1772                     // Client explicitly called disconnect, do not invoke the callbacks.
1773                     return;
1774                 }
1775             }
1776 
1777             mMainThreadEventHandler.post(() -> setBinderAndNotifyReady(binder));
1778         }
1779     }
1780 
1781     private final ServiceConnection mServiceConnectionListener = new ServiceConnection() {
1782         @Override
1783         public void onServiceConnected(ComponentName name, IBinder service) {
1784             synchronized (mLock) {
1785                 ICar newService = ICar.Stub.asInterface(service);
1786                 if (newService == null) {
1787                     Slog.wtf(TAG_CAR, "null binder service", new RuntimeException());
1788                     return;  // should not happen.
1789                 }
1790                 if (mService != null) {
1791                     if (mService.asBinder().equals(newService.asBinder())) {
1792                         // already connected.
1793                         return;
1794                     } else {
1795                         // The binder handle has changed, indicating that CarService has restarted.
1796                         // This Car client object is now attached to a different instance than
1797                         // when it was originally instantiated. We need to process the
1798                         // onServiceDisconnected() event for the previous connection instance.
1799                         onServiceDisconnected(name);
1800                     }
1801                 }
1802                 mConnectionState = STATE_CONNECTED;
1803                 mService = newService;
1804             }
1805             Slog.i(TAG_CAR, "car_service ready on main thread, Time between Car object creation "
1806                     + "and car_service connected (ms): " + timeSinceCreateMillis());
1807             if (mStatusChangeCallback != null) {
1808                 mStatusChangeCallback.onLifecycleChanged(Car.this, /* ready= */ true);
1809             } else if (mServiceConnectionListenerClient != null) {
1810                 mServiceConnectionListenerClient.onServiceConnected(name, service);
1811             }
1812         }
1813 
1814         @Override
1815         public void onServiceDisconnected(ComponentName name) {
1816             // Car service can pick up feature changes after restart.
1817             Slog.w(TAG_CAR, "Car service disconnected, probably crashed");
1818             mFeatures.resetCache();
1819             synchronized (mLock) {
1820                 if (mConnectionState == STATE_DISCONNECTED) {
1821                     // can happen when client calls disconnect before onServiceDisconnected call.
1822                     return;
1823                 }
1824                 handleCarDisconnectLocked();
1825             }
1826             if (mStatusChangeCallback != null) {
1827                 mStatusChangeCallback.onLifecycleChanged(Car.this, /* ready= */ false);
1828             } else if (mServiceConnectionListenerClient != null) {
1829                 mServiceConnectionListenerClient.onServiceDisconnected(name);
1830             } else {
1831                 // This client does not handle car service restart, so should be terminated.
1832                 finishClient();
1833             }
1834         }
1835     };
1836 
1837     private final IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
1838         @Override
1839         public void binderDied() {
1840             Slog.w(TAG_CAR, "Car service disconnected, probably crashed");
1841             // Car service can pick up feature changes after restart.
1842             mFeatures.resetCache();
1843             synchronized (mLock) {
1844                 if (mConnectionState == STATE_DISCONNECTED) {
1845                     Slog.i(TAG_CAR, "State is already disconnected, ignore");
1846                     // can happen when client calls disconnect before onServiceDisconnected call.
1847                     return;
1848                 }
1849                 mCarServiceBinder = null;
1850                 handleCarDisconnectLocked();
1851             }
1852             dispatchToMainThread(isMainThread(), () -> notifyCarDisconnected());
1853             registerServiceListenerIfNotRegistered();
1854         }
1855     };
1856 
1857     @Nullable
1858     private final ServiceConnection mServiceConnectionListenerClient;
1859 
1860     /** Can be added after ServiceManagerHelper.getService call */
1861     @Nullable
1862     private final CarServiceLifecycleListener mStatusChangeCallback;
1863 
1864     @GuardedBy("mLock")
1865     private final HashMap<String, CarManagerBase> mServiceMap = new HashMap<>();
1866 
1867     /** Handler for generic event dispatching. */
1868     private final Handler mEventHandler;
1869 
1870     private final Handler mMainThreadEventHandler;
1871 
1872     private final CarFeatures mFeatures = new CarFeatures();
1873 
1874     /**
1875      * The dependencies used by this class.
1876      *
1877      * @hide
1878      */
1879     @VisibleForTesting
Deps(ServiceManager serviceManager, Process process, long carServiceBindRetryIntervalMs, long carServiceBindMaxRetry, long createCarDefaultTimeoutMs)1880     public record Deps(ServiceManager serviceManager, Process process,
1881             long carServiceBindRetryIntervalMs, long carServiceBindMaxRetry,
1882             long createCarDefaultTimeoutMs) {}
1883 
1884     // Real system dependencies.
1885     private static final Deps SYSTEM_DEPS = new Deps(
1886             new SystemServiceManager(), new SystemProcess(),
1887             CAR_SERVICE_BIND_RETRY_INTERVAL_MS, CAR_SERVICE_BIND_MAX_RETRY,
1888             CREATE_CAR_DEFAULT_TIMEOUT_MS);
1889 
1890     private final Deps mDeps;
1891 
1892     static {
CAR_SERVICE_NAMES.put(CarSensorManager.class, SENSOR_SERVICE)1893         CAR_SERVICE_NAMES.put(CarSensorManager.class, SENSOR_SERVICE);
CAR_SERVICE_NAMES.put(CarInfoManager.class, INFO_SERVICE)1894         CAR_SERVICE_NAMES.put(CarInfoManager.class, INFO_SERVICE);
CAR_SERVICE_NAMES.put(CarAppFocusManager.class, APP_FOCUS_SERVICE)1895         CAR_SERVICE_NAMES.put(CarAppFocusManager.class, APP_FOCUS_SERVICE);
CAR_SERVICE_NAMES.put(CarPackageManager.class, PACKAGE_SERVICE)1896         CAR_SERVICE_NAMES.put(CarPackageManager.class, PACKAGE_SERVICE);
CAR_SERVICE_NAMES.put(CarAudioManager.class, AUDIO_SERVICE)1897         CAR_SERVICE_NAMES.put(CarAudioManager.class, AUDIO_SERVICE);
CAR_SERVICE_NAMES.put(CarNavigationStatusManager.class, CAR_NAVIGATION_SERVICE)1898         CAR_SERVICE_NAMES.put(CarNavigationStatusManager.class, CAR_NAVIGATION_SERVICE);
CAR_SERVICE_NAMES.put(CarOccupantZoneManager.class, CAR_OCCUPANT_ZONE_SERVICE)1899         CAR_SERVICE_NAMES.put(CarOccupantZoneManager.class, CAR_OCCUPANT_ZONE_SERVICE);
CAR_SERVICE_NAMES.put(CarUserManager.class, CAR_USER_SERVICE)1900         CAR_SERVICE_NAMES.put(CarUserManager.class, CAR_USER_SERVICE);
CAR_SERVICE_NAMES.put(CarDevicePolicyManager.class, CAR_DEVICE_POLICY_SERVICE)1901         CAR_SERVICE_NAMES.put(CarDevicePolicyManager.class, CAR_DEVICE_POLICY_SERVICE);
CAR_SERVICE_NAMES.put(CarInstrumentClusterManager.class, CAR_INSTRUMENT_CLUSTER_SERVICE)1902         CAR_SERVICE_NAMES.put(CarInstrumentClusterManager.class, CAR_INSTRUMENT_CLUSTER_SERVICE);
CAR_SERVICE_NAMES.put(CarCabinManager.class, CABIN_SERVICE)1903         CAR_SERVICE_NAMES.put(CarCabinManager.class, CABIN_SERVICE);
CAR_SERVICE_NAMES.put(CarDiagnosticManager.class, DIAGNOSTIC_SERVICE)1904         CAR_SERVICE_NAMES.put(CarDiagnosticManager.class, DIAGNOSTIC_SERVICE);
CAR_SERVICE_NAMES.put(CarHvacManager.class, HVAC_SERVICE)1905         CAR_SERVICE_NAMES.put(CarHvacManager.class, HVAC_SERVICE);
CAR_SERVICE_NAMES.put(CarPowerManager.class, POWER_SERVICE)1906         CAR_SERVICE_NAMES.put(CarPowerManager.class, POWER_SERVICE);
CAR_SERVICE_NAMES.put(CarProjectionManager.class, PROJECTION_SERVICE)1907         CAR_SERVICE_NAMES.put(CarProjectionManager.class, PROJECTION_SERVICE);
CAR_SERVICE_NAMES.put(CarPropertyManager.class, PROPERTY_SERVICE)1908         CAR_SERVICE_NAMES.put(CarPropertyManager.class, PROPERTY_SERVICE);
CAR_SERVICE_NAMES.put(CarVendorExtensionManager.class, VENDOR_EXTENSION_SERVICE)1909         CAR_SERVICE_NAMES.put(CarVendorExtensionManager.class, VENDOR_EXTENSION_SERVICE);
CAR_SERVICE_NAMES.put(VmsClientManager.class, VEHICLE_MAP_SERVICE)1910         CAR_SERVICE_NAMES.put(VmsClientManager.class, VEHICLE_MAP_SERVICE);
CAR_SERVICE_NAMES.put(VmsSubscriberManager.class, VMS_SUBSCRIBER_SERVICE)1911         CAR_SERVICE_NAMES.put(VmsSubscriberManager.class, VMS_SUBSCRIBER_SERVICE);
CAR_SERVICE_NAMES.put(CarDrivingStateManager.class, CAR_DRIVING_STATE_SERVICE)1912         CAR_SERVICE_NAMES.put(CarDrivingStateManager.class, CAR_DRIVING_STATE_SERVICE);
CAR_SERVICE_NAMES.put(CarUxRestrictionsManager.class, CAR_UX_RESTRICTION_SERVICE)1913         CAR_SERVICE_NAMES.put(CarUxRestrictionsManager.class, CAR_UX_RESTRICTION_SERVICE);
CAR_SERVICE_NAMES.put(OccupantAwarenessManager.class, OCCUPANT_AWARENESS_SERVICE)1914         CAR_SERVICE_NAMES.put(OccupantAwarenessManager.class, OCCUPANT_AWARENESS_SERVICE);
CAR_SERVICE_NAMES.put(CarMediaManager.class, CAR_MEDIA_SERVICE)1915         CAR_SERVICE_NAMES.put(CarMediaManager.class, CAR_MEDIA_SERVICE);
CAR_SERVICE_NAMES.put(CarBugreportManager.class, CAR_BUGREPORT_SERVICE)1916         CAR_SERVICE_NAMES.put(CarBugreportManager.class, CAR_BUGREPORT_SERVICE);
CAR_SERVICE_NAMES.put(CarStorageMonitoringManager.class, STORAGE_MONITORING_SERVICE)1917         CAR_SERVICE_NAMES.put(CarStorageMonitoringManager.class, STORAGE_MONITORING_SERVICE);
CAR_SERVICE_NAMES.put(CarWatchdogManager.class, CAR_WATCHDOG_SERVICE)1918         CAR_SERVICE_NAMES.put(CarWatchdogManager.class, CAR_WATCHDOG_SERVICE);
CAR_SERVICE_NAMES.put(CarPerformanceManager.class, CAR_PERFORMANCE_SERVICE)1919         CAR_SERVICE_NAMES.put(CarPerformanceManager.class, CAR_PERFORMANCE_SERVICE);
CAR_SERVICE_NAMES.put(CarInputManager.class, CAR_INPUT_SERVICE)1920         CAR_SERVICE_NAMES.put(CarInputManager.class, CAR_INPUT_SERVICE);
CAR_SERVICE_NAMES.put(ClusterHomeManager.class, CLUSTER_HOME_SERVICE)1921         CAR_SERVICE_NAMES.put(ClusterHomeManager.class, CLUSTER_HOME_SERVICE);
CAR_SERVICE_NAMES.put(CarTestManager.class, TEST_SERVICE)1922         CAR_SERVICE_NAMES.put(CarTestManager.class, TEST_SERVICE);
CAR_SERVICE_NAMES.put(CarEvsManager.class, CAR_EVS_SERVICE)1923         CAR_SERVICE_NAMES.put(CarEvsManager.class, CAR_EVS_SERVICE);
CAR_SERVICE_NAMES.put(CarTelemetryManager.class, CAR_TELEMETRY_SERVICE)1924         CAR_SERVICE_NAMES.put(CarTelemetryManager.class, CAR_TELEMETRY_SERVICE);
CAR_SERVICE_NAMES.put(CarActivityManager.class, CAR_ACTIVITY_SERVICE)1925         CAR_SERVICE_NAMES.put(CarActivityManager.class, CAR_ACTIVITY_SERVICE);
CAR_SERVICE_NAMES.put(CarRemoteAccessManager.class, CAR_REMOTE_ACCESS_SERVICE)1926         CAR_SERVICE_NAMES.put(CarRemoteAccessManager.class, CAR_REMOTE_ACCESS_SERVICE);
CAR_SERVICE_NAMES.put(CarOccupantConnectionManager.class, CAR_OCCUPANT_CONNECTION_SERVICE)1927         CAR_SERVICE_NAMES.put(CarOccupantConnectionManager.class, CAR_OCCUPANT_CONNECTION_SERVICE);
CAR_SERVICE_NAMES.put(CarRemoteDeviceManager.class, CAR_REMOTE_DEVICE_SERVICE)1928         CAR_SERVICE_NAMES.put(CarRemoteDeviceManager.class, CAR_REMOTE_DEVICE_SERVICE);
1929         if (Flags.persistApSettings()) {
CAR_SERVICE_NAMES.put(CarWifiManager.class, CAR_WIFI_SERVICE)1930             CAR_SERVICE_NAMES.put(CarWifiManager.class, CAR_WIFI_SERVICE);
1931         }
1932         if (Flags.displayCompatibility()) {
CAR_SERVICE_NAMES.put(CarDisplayCompatManager.class, CAR_DISPLAY_COMPAT_SERVICE)1933             CAR_SERVICE_NAMES.put(CarDisplayCompatManager.class, CAR_DISPLAY_COMPAT_SERVICE);
1934         }
1935         if (Flags.carPropertySimulation()) {
CAR_SERVICE_NAMES.put(CarPropertySimulationManager.class, CAR_PROPERTY_SIMULATION_SERVICE)1936             CAR_SERVICE_NAMES.put(CarPropertySimulationManager.class,
1937                     CAR_PROPERTY_SIMULATION_SERVICE);
1938         }
1939         // Note: if a new entry is added here, the capacity of CAR_SERVICE_NAMES should be increased
1940         // as well.
1941     }
1942 
1943     /**
1944      * Defines the {@link CarVersion version} of the {@code Car} APIs in the device.
1945      *
1946      * <p>Starting on {@link android.os.Build.VERSION_CODES#TIRAMISU Android 13}, the {@code Car}
1947      * APIs can be upgraded without an OTA, so it's possible that these APIs are higher than the
1948      * {@link #getPlatformVersion() platform's}.
1949      *
1950      * @deprecated - use {@code android.os.Build.VERSION#SDK_INT} instead
1951      */
1952     @NonNull
1953     @Deprecated
getCarVersion()1954     public static android.car.CarVersion getCarVersion() {
1955         return CAR_VERSION;
1956     }
1957 
1958     /**
1959      * Defines the {@link PlatformVersion version} of the standard {@code SDK} APIs in the
1960      * device.
1961      *
1962      * <p>Its {@link ApiVersion#getMajorVersion() major version} will be the same as
1963      * {@link android.os.Build.VERSION#SDK_INT} for released build but will be
1964      * {@link android.os.Build.VERSION_CODES#CUR_DEVELOPMENT} for platform still under development.
1965      *
1966      * @deprecated - use {@code android.os.Build.VERSION#SDK_INT} instead
1967      */
1968     @NonNull
1969     @Deprecated
getPlatformVersion()1970     public static android.car.PlatformVersion getPlatformVersion() {
1971         return PLATFORM_VERSION;
1972     }
1973 
1974     /**
1975      * @deprecated - use {@code getCarApiVersion().isAtLeast(CarVersion.forMajorAndMinorVersions(
1976      * requiredApiVersionMajor))} instead
1977      */
1978     @Deprecated
isApiVersionAtLeast(int requiredApiVersionMajor)1979     public static boolean isApiVersionAtLeast(int requiredApiVersionMajor) {
1980         return getCarVersion().isAtLeast(CarVersion.forMajorVersion(requiredApiVersionMajor));
1981     }
1982 
1983     /**
1984      * @deprecated - use {@code getCarVersion().isAtLeast(CarVersion.forMajorAndMinorVersions(
1985      * requiredApiVersionMajor, requiredApiVersionMinor)} instead
1986      */
1987     @Deprecated
isApiVersionAtLeast(int requiredApiVersionMajor, int requiredApiVersionMinor)1988     public static boolean isApiVersionAtLeast(int requiredApiVersionMajor,
1989             int requiredApiVersionMinor) {
1990         return getCarVersion()
1991                 .isAtLeast(CarVersion.forMajorAndMinorVersions(requiredApiVersionMajor,
1992                         requiredApiVersionMinor));
1993     }
1994 
1995     /**
1996      * @deprecated - use
1997      * {@code getCarVersion().isAtLeast(CarVersion.forMajorVersion(requiredApiVersionMajor))
1998      * && getPlatformVersion().isAtLeast(PlatformVersion.forMajorVersion(minPlatformSdkInt))}
1999      * instead.
2000      */
2001     @Deprecated
isApiAndPlatformVersionAtLeast(int requiredApiVersionMajor, int minPlatformSdkInt)2002     public static boolean isApiAndPlatformVersionAtLeast(int requiredApiVersionMajor,
2003             int minPlatformSdkInt) {
2004         return getCarVersion().isAtLeast(CarVersion.forMajorVersion(requiredApiVersionMajor))
2005                 && getPlatformVersion()
2006                         .isAtLeast(PlatformVersion.forMajorVersion(minPlatformSdkInt));
2007     }
2008 
2009     /**
2010      * @deprecated - use {@code getCarVersion().isAtLeast(CarVersion.forMajorAndMinorVersions(
2011      * requiredApiVersionMajor, requiredApiVersionMinor)) && getPlatformVersion().isAtLeast(
2012      * PlatformVersion.forMajorVersion(minPlatformSdkInt))} instead.
2013      */
2014     @Deprecated
isApiAndPlatformVersionAtLeast(int requiredApiVersionMajor, int requiredApiVersionMinor, int minPlatformSdkInt)2015     public static boolean isApiAndPlatformVersionAtLeast(int requiredApiVersionMajor,
2016             int requiredApiVersionMinor, int minPlatformSdkInt) {
2017         return getCarVersion()
2018                 .isAtLeast(CarVersion.forMajorAndMinorVersions(requiredApiVersionMajor,
2019                         requiredApiVersionMinor))
2020                 && getPlatformVersion()
2021                         .isAtLeast(PlatformVersion.forMajorVersion(minPlatformSdkInt));
2022     }
2023 
2024     /**
2025      * A factory method that creates Car instance for all Car API access.
2026      *
2027      * <p>Instance created with this should be disconnected from car service by calling
2028      * {@link #disconnect()} before the passed {@code Context} is released.
2029      *
2030      * @param context This should not be {@code null}. If you are passing {@link ContextWrapper},
2031      *                make sure that its {@link ContextWrapper#getBaseContext() base context} is not
2032      *                {@code null} as well.
2033      *                Otherwise it will throw {@link java.lang.NullPointerException}.
2034      * @param serviceConnectionListener listener for monitoring service connection. It is allowed
2035      * but not recommended to pass {@code null}. If this is {@code null}, client has to periodically
2036      * check {@link #isConnected()} to know when car service is connected.
2037      * @param handler the handler on which the callback should execute, or null to execute on the
2038      * service's main thread. Note: the service connection listener will be always on the main
2039      * thread regardless of the handler given.
2040      * @return Car instance if system is in car environment and returns {@code null} otherwise.
2041      *
2042      * @deprecated use {@link #createCar(Context, Handler)} instead.
2043      */
2044     @Deprecated
createCar(Context context, ServiceConnection serviceConnectionListener, @Nullable Handler handler)2045     public static Car createCar(Context context, ServiceConnection serviceConnectionListener,
2046             @Nullable Handler handler) {
2047         return new CarBuilder().createCar(context, serviceConnectionListener, handler);
2048     }
2049 
2050     /**
2051      * A factory method that creates Car instance for all Car API access using main thread {@code
2052      * Looper}.
2053      *
2054      * <p>Instance created with this should be disconnected from car service by calling
2055      * {@link #disconnect()} before the passed {@code Context} is released.
2056      *
2057      * @see #createCar(Context, ServiceConnection, Handler)
2058      *
2059      * @deprecated use {@link #createCar(Context, Handler)} instead.
2060      */
2061     @Deprecated
createCar(Context context, ServiceConnection serviceConnectionListener)2062     public static Car createCar(Context context, ServiceConnection serviceConnectionListener) {
2063         return new CarBuilder().createCar(context, serviceConnectionListener);
2064     }
2065 
2066     /**
2067      * Creates new {@link Car} object which connected synchronously to Car Service and ready to use.
2068      *
2069      * <p>Instance created with this should be disconnected from car service by calling
2070      * {@link #disconnect()} before the passed {@code Context} is released.
2071      *
2072      * @param context application's context
2073      *
2074      * @return Car object if operation succeeded, otherwise null.
2075      */
2076     @Nullable
createCar(Context context)2077     public static Car createCar(Context context) {
2078         return new CarBuilder().createCar(context);
2079     }
2080 
2081     /**
2082      * Creates new {@link Car} object which connected synchronously to Car Service and ready to use.
2083      *
2084      * <p>Instance created with this should be disconnected from car service by calling
2085      * {@link #disconnect()} before the passed {@code Context} is released.
2086      *
2087      * @param context This should not be {@code null}. If you are passing {@link ContextWrapper},
2088      *                make sure that its {@link ContextWrapper#getBaseContext() base context} is not
2089      *                {@code null} as well.
2090      *                Otherwise it will throw {@link java.lang.NullPointerException}.
2091      * @param handler the handler on which the manager's callbacks will be executed, or null to
2092      * execute on the application's main thread.
2093      *
2094      * @return Car object if operation succeeded, otherwise null.
2095      */
2096     @Nullable
createCar(Context context, @Nullable Handler handler)2097     public static Car createCar(Context context, @Nullable Handler handler) {
2098         return new CarBuilder().createCar(context, handler);
2099     }
2100 
2101     /**
2102      * Creates new {@link Car} object with {@link CarServiceLifecycleListener}.
2103      *
2104      * <p>Instance created with this should be disconnected from car service by calling
2105      * {@link #disconnect()} before the passed {@code Context} is released.
2106      *
2107      * <p> If car service is ready inside this call and if the caller is running in the main thread,
2108      * {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} will be called
2109      * with ready set to be true. Otherwise,
2110      * {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} will be called
2111      * from the main thread later. </p>
2112      *
2113      * <p>This call can block up to specified waitTimeoutMs to wait for car service to be ready.
2114      * If car service is not ready within the given time, it will return a Car instance in
2115      * disconnected state. Blocking main thread forever can lead into getting ANR (Application Not
2116      * Responding) killing from system and should not be used if the app is supposed to survive
2117      * across the crash / restart of car service. It can be still useful in case the app cannot do
2118      * anything without car service being ready. In any waiting, if the thread is getting
2119      * interrupted, it will return immediately.
2120      * </p>
2121      *
2122      * <p>Note that returned {@link Car} object is not guaranteed to be connected when there is
2123      * a limited timeout. Regardless of returned car being connected or not, it is recommended to
2124      * implement all car related initialization inside
2125      * {@link CarServiceLifecycleListener#onLifecycleChanged(Car, boolean)} and avoid the
2126      * needs to check if returned {@link Car} is connected or not from returned {@link Car}.</p>
2127      *
2128      * @param context This should not be {@code null}. If you are passing {@link ContextWrapper},
2129      *                make sure that its {@link ContextWrapper#getBaseContext() base context} is not
2130      *                {@code null} as well.
2131      *                Otherwise it will throw {@link java.lang.NullPointerException}.
2132      * @param handler dispatches all Car*Manager events to this Handler. Exception is
2133      *                {@link CarServiceLifecycleListener} which will be always dispatched to main
2134      *                thread. Passing null leads into dispatching all Car*Manager callbacks to main
2135      *                thread as well.
2136      * @param waitTimeoutMs Setting this to {@link #CAR_WAIT_TIMEOUT_DO_NOT_WAIT} will guarantee
2137      *                      that the API does not wait for the car service at all. Setting this to
2138      *                      to {@link #CAR_WAIT_TIMEOUT_WAIT_FOREVER} will block the call forever
2139      *                      until the car service is ready. Setting any positive value will be
2140      *                      interpreted as timeout value.
2141      */
2142     @NonNull
createCar(@onNull Context context, @Nullable Handler handler, long waitTimeoutMs, @NonNull CarServiceLifecycleListener statusChangeListener)2143     public static Car createCar(@NonNull Context context, @Nullable Handler handler,
2144             long waitTimeoutMs, @NonNull CarServiceLifecycleListener statusChangeListener) {
2145         return new CarBuilder().createCar(context, handler, waitTimeoutMs, statusChangeListener);
2146     }
2147 
2148     /**
2149      * A wrapper around {@code createCar} functions that allows injecting deps for testing.
2150      *
2151      * @hide
2152      */
2153     @VisibleForTesting
2154     public static final class CarBuilder {
2155         private Deps mDeps = SYSTEM_DEPS;
2156 
2157         /**
2158          * Sets the fake dependencies for testing.
2159          */
setFakeDeps(Deps deps)2160         public CarBuilder setFakeDeps(Deps deps) {
2161             mDeps = deps;
2162             return this;
2163         }
2164 
2165         /**
2166          * See {@link Car#createCar}.
2167          *
2168          * Even though serviceConnectionListener is not marked as Nullable, existing client may
2169          * pass null.
2170          */
2171         @Nullable
createCar(Context context, @Nullable ServiceConnection serviceConnectionListener)2172         public Car createCar(Context context,
2173                 @Nullable ServiceConnection serviceConnectionListener) {
2174             return createCar(context, serviceConnectionListener, /* handler= */ null);
2175         }
2176 
2177         /**
2178          * See {@link Car#createCar}.
2179          */
2180         @Nullable
createCar(Context context, @Nullable ServiceConnection serviceConnectionListener, @Nullable Handler handler)2181         public Car createCar(Context context, @Nullable ServiceConnection serviceConnectionListener,
2182                 @Nullable Handler handler) {
2183             assertNonNullContext(context);
2184             if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
2185                 Slog.e(TAG_CAR, "FEATURE_AUTOMOTIVE not declared while android.car is used");
2186                 return null;
2187             }
2188             try {
2189                 return new Car(context, /* service= */ null , serviceConnectionListener,
2190                         /* statusChangeListener= */ null, handler, mDeps);
2191             } catch (IllegalArgumentException e) {
2192                 // Expected when car service loader is not available.
2193             }
2194             return null;
2195         }
2196 
2197         /**
2198          * See {@link Car#createCar}.
2199          */
2200         @Nullable
createCar(Context context)2201         public Car createCar(Context context) {
2202             return createCar(context, (Handler) null);
2203         }
2204 
2205         /**
2206          * See {@link Car#createCar}.
2207          */
2208         @Nullable
createCar(Context context, @Nullable Handler handler)2209         public Car createCar(Context context, @Nullable Handler handler) {
2210             assertNonNullContext(context);
2211 
2212             if (Flags.createCarUseNotifications()) {
2213                 // New optimized logic.
2214                 return createCarInternal(context, handler, mDeps.createCarDefaultTimeoutMs,
2215                         /* statusChangeListener= */ null);
2216             }
2217 
2218             return createCarInternalLegacy(context, handler);
2219         }
2220 
2221         /**
2222          * See {@link Car#createCar}.
2223          */
2224         @NonNull
createCar(@onNull Context context, @Nullable Handler handler, long waitTimeoutMs, @NonNull CarServiceLifecycleListener statusChangeListener)2225         public Car createCar(@NonNull Context context, @Nullable Handler handler,
2226                 long waitTimeoutMs, @NonNull CarServiceLifecycleListener statusChangeListener) {
2227             assertNonNullContext(context);
2228             Objects.requireNonNull(statusChangeListener);
2229 
2230             if (Flags.createCarUseNotifications()) {
2231                 // New optimized logic.
2232                 // statusChangeListener is not null, so this must not return null.
2233                 return createCarInternal(context, handler, waitTimeoutMs, statusChangeListener);
2234             }
2235 
2236             return createCarInternalLegacy(context, handler, waitTimeoutMs, statusChangeListener);
2237         }
2238 
createCarInternal(Context context, @Nullable Handler handler, long waitTimeoutMs, @Nullable CarServiceLifecycleListener statusChangeListener)2239         private @Nullable Car createCarInternal(Context context,
2240                 @Nullable Handler handler, long waitTimeoutMs,
2241                 @Nullable CarServiceLifecycleListener statusChangeListener) {
2242             Car car = new Car(context, /* service= */ null, /* serviceConnectionListener= */ null,
2243                     statusChangeListener, handler, mDeps);
2244             IBinder binderService = mDeps.serviceManager().getService(
2245                     CAR_SERVICE_BINDER_SERVICE_NAME);
2246             if (binderService != null) {
2247                 // Most common case when car service is already ready.
2248                 if (car.setCarService(binderService)) {
2249                     Slogf.i(TAG_CAR, "createCar: car_service is already ready, took (ms): %d",
2250                             car.timeSinceCreateMillis());
2251                     car.notifyCarReadyOnMainThread(binderService);
2252                     return car;
2253                 } else {
2254                     // If the binder is already dead, we ignore it and keep waiting.
2255                     Slogf.w(TAG_CAR, "createCar: the binder returned from serviceManager."
2256                             + "getService is already dead, ignore the binder");
2257                 }
2258             }
2259 
2260             car.registerServiceListenerIfNotRegistered();
2261             IBinder serviceBinder = car.waitForCarServiceReady(waitTimeoutMs);
2262 
2263             if (serviceBinder == null) {
2264                 Slog.w(TAG_CAR,
2265                         "createCar: (waitTimeoutMs=" + waitTimeoutMs
2266                         + ") car_service not ready, took (ms):"
2267                         + car.timeSinceCreateMillis());
2268                 if (statusChangeListener == null) {
2269                     return null;
2270                 }
2271                 // Return a car instance that is not connected to the car service.
2272                 return car;
2273             }
2274 
2275             Slog.i(TAG_CAR, "createCar: (waitTimeoutMs=" + waitTimeoutMs
2276                     + ") connected to car_service, took (ms): "
2277                     + car.timeSinceCreateMillis());
2278             car.notifyCarReadyOnMainThread(serviceBinder);
2279             return car;
2280         }
2281 
getMaxRetryCount(long timeoutMs, long intervalMs)2282         private static long getMaxRetryCount(long timeoutMs, long intervalMs) {
2283             long maxRetryCount = timeoutMs / intervalMs;
2284             if (timeoutMs > 0 && maxRetryCount == 0) {
2285                 // at least retry once.
2286                 maxRetryCount = 1;
2287             }
2288             return maxRetryCount;
2289         }
2290 
2291         // Legacy createCar implementation.
createCarInternalLegacy(Context context, @Nullable Handler handler)2292         private @Nullable Car createCarInternalLegacy(Context context, @Nullable Handler handler) {
2293             Car car = null;
2294             IBinder service = null;
2295             boolean started = false;
2296             long retryCount = 0;
2297             long maxRetryCount = getMaxRetryCount(mDeps.createCarDefaultTimeoutMs,
2298                     CAR_SERVICE_BINDER_POLLING_INTERVAL_MS);
2299             while (true) {
2300                 service = mDeps.serviceManager().getService(CAR_SERVICE_BINDER_SERVICE_NAME);
2301                 if (car == null) {
2302                     // service can be still null. The constructor is safe for null service.
2303                     car = new Car(context, ICar.Stub.asInterface(service),
2304                             null /*serviceConnectionListener*/, null /*statusChangeListener*/,
2305                             handler, mDeps);
2306                 }
2307                 if (service != null) {
2308                     if (!started) {  // specialization for most common case.
2309                         // Do this to crash client when car service crashes.
2310                         car.startCarService();
2311                         return car;
2312                     }
2313                     break;
2314                 }
2315                 if (!started) {
2316                     car.startCarService();
2317                     started = true;
2318                 }
2319                 retryCount++;
2320                 if (retryCount > maxRetryCount) {
2321                     Slog.e(TAG_CAR, "cannot get car_service, waited for car service (ms):"
2322                                     + mDeps.createCarDefaultTimeoutMs,
2323                             new RuntimeException());
2324                     return null;
2325                 }
2326                 try {
2327                     Thread.sleep(CAR_SERVICE_BINDER_POLLING_INTERVAL_MS);
2328                 } catch (InterruptedException e) {
2329                     Slog.e(CarLibLog.TAG_CAR, "interrupted while waiting for car_service",
2330                             new RuntimeException());
2331                     return null;
2332                 }
2333             }
2334             // Can be accessed from mServiceConnectionListener in main thread.
2335             synchronized (car.mLock) {
2336                 if (car.mService == null) {
2337                     car.mService = ICar.Stub.asInterface(service);
2338                     Slog.w(TAG_CAR,
2339                             "waited for car_service (ms):"
2340                                     + CAR_SERVICE_BINDER_POLLING_INTERVAL_MS * retryCount,
2341                             new RuntimeException());
2342                 }
2343                 car.mConnectionState = STATE_CONNECTED;
2344             }
2345             return car;
2346         }
2347 
2348         // Legacy createCar implementation.
createCarInternalLegacy(@onNull Context context, @Nullable Handler handler, long waitTimeoutMs, @NonNull CarServiceLifecycleListener statusChangeListener)2349         private Car createCarInternalLegacy(@NonNull Context context,
2350                 @Nullable Handler handler, long waitTimeoutMs,
2351                 @NonNull CarServiceLifecycleListener statusChangeListener) {
2352             Car car = null;
2353             IBinder service = null;
2354             boolean started = false;
2355             int retryCount = 0;
2356             long maxRetryCount = 0;
2357             if (waitTimeoutMs > 0) {
2358                 maxRetryCount = getMaxRetryCount(waitTimeoutMs,
2359                     CAR_SERVICE_BINDER_POLLING_INTERVAL_MS);
2360             } else if (waitTimeoutMs < 0) {
2361                 maxRetryCount = getMaxRetryCount(CREATE_CAR_DEFAULT_TIMEOUT_MS,
2362                     CAR_SERVICE_BINDER_POLLING_INTERVAL_MS);
2363             }
2364             boolean isMainThread = Looper.myLooper() == Looper.getMainLooper();
2365             while (true) {
2366                 service = mDeps.serviceManager().getService(CAR_SERVICE_BINDER_SERVICE_NAME);
2367                 if (car == null) {
2368                     // service can be still null. The constructor is safe for null service.
2369                     car = new Car(context, ICar.Stub.asInterface(service), null,
2370                             statusChangeListener, handler, mDeps);
2371                 }
2372                 if (service != null) {
2373                     // specialization for most common case : car service already ready
2374                     if (!started) {
2375                         car.dispatchCarReadyToMainThread(isMainThread);
2376                         // Needs this for CarServiceLifecycleListener. Note that ServiceConnection
2377                         // will skip the callback as valid mService is set already.
2378                         car.startCarService();
2379                         return car;
2380                     }
2381                     // service available after starting.
2382                     break;
2383                 }
2384                 if (!started) {
2385                     car.startCarService();
2386                     started = true;
2387                 }
2388                 retryCount++;
2389                 if (waitTimeoutMs < 0 && retryCount >= maxRetryCount
2390                         && retryCount % maxRetryCount == 0) {
2391                     // Log warning if car service is not alive even for waiting forever case.
2392                     Slog.w(TAG_CAR, "car_service not ready, waited for car service (ms):"
2393                                     + retryCount * CAR_SERVICE_BINDER_POLLING_INTERVAL_MS,
2394                             new RuntimeException("create_car wait info, not a real exception"));
2395                 } else if (waitTimeoutMs >= 0 && retryCount > maxRetryCount) {
2396                     if (waitTimeoutMs > 0) {
2397                         Slog.w(TAG_CAR, "car_service not ready, waited for car service (ms):"
2398                                         + waitTimeoutMs,
2399                                 new RuntimeException());
2400                     }
2401                     return car;
2402                 }
2403 
2404                 try {
2405                     Thread.sleep(CAR_SERVICE_BINDER_POLLING_INTERVAL_MS);
2406                 } catch (InterruptedException e) {
2407                     Thread.currentThread().interrupt();
2408                     Slog.w(TAG_CAR, "interrupted", new RuntimeException());
2409                     return car;
2410                 }
2411             }
2412             // Can be accessed from mServiceConnectionListener in main thread.
2413             synchronized (car.mLock) {
2414                 Slog.w(TAG_CAR,
2415                         "waited for car_service (ms):"
2416                                 + retryCount * CAR_SERVICE_BINDER_POLLING_INTERVAL_MS,
2417                         new RuntimeException());
2418                 // ServiceConnection has handled everything.
2419                 if (car.mService != null) {
2420                     return car;
2421                 }
2422                 // mService check in ServiceConnection prevents calling
2423                 // onLifecycleChanged. So onLifecycleChanged should be called explicitly
2424                 // but do it outside lock.
2425                 car.mService = ICar.Stub.asInterface(service);
2426                 car.mConnectionState = STATE_CONNECTED;
2427             }
2428             Slog.i(TAG_CAR, "createCar: car_service is ready, took (ms): "
2429                     + car.timeSinceCreateMillis());
2430             car.dispatchCarReadyToMainThread(isMainThread);
2431             return car;
2432         }
2433     }
2434 
timeSinceCreateMillis()2435     private long timeSinceCreateMillis() {
2436         return SystemClock.uptimeMillis() - mCreateUptimeMillis;
2437     }
2438 
registerServiceListenerIfNotRegistered()2439     private void registerServiceListenerIfNotRegistered() {
2440         synchronized (mLock) {
2441             if (mServiceListenerRegistered) {
2442                 return;
2443             }
2444             try {
2445                 mDeps.serviceManager().registerForNotifications(CAR_SERVICE_BINDER_SERVICE_NAME,
2446                         mServiceRegistrationCallback);
2447             } catch (RemoteException e) {
2448                 Slog.e(TAG_CAR, "failed to call ServiceManager.registerForNotifications", e);
2449                 return;
2450             }
2451             mServiceListenerRegistered = true;
2452             return;
2453         }
2454     }
2455 
2456     @GuardedBy("mLock")
waitForCarServiceBinderNoTimeoutLocked()2457     private void waitForCarServiceBinderNoTimeoutLocked() throws InterruptedException {
2458         // First wait for 5s.
2459         waitForCarServiceBinderLocked(mDeps.createCarDefaultTimeoutMs);
2460         if (mCarServiceBinder != null) {
2461             return;
2462         }
2463         // Log warning if car service is not alive even for waiting forever case.
2464         Slog.w(TAG_CAR,
2465                 "createCar: (wait indefinitely) still cannot get car_service after "
2466                 + mDeps.createCarDefaultTimeoutMs + "ms");
2467         // If we still cannot get car service, then wait forever.
2468         while (mCarServiceBinder == null) {
2469             // await in a loop to prevent spurious wakeup.
2470             mLock.wait();
2471         }
2472     }
2473 
2474     @GuardedBy("mLock")
waitForCarServiceBinderLocked(long waitTimeoutMs)2475     private void waitForCarServiceBinderLocked(long waitTimeoutMs) throws InterruptedException {
2476         long deadlineMillis = SystemClock.uptimeMillis() + waitTimeoutMs;
2477         while (mCarServiceBinder == null) {
2478             long uptimeMillis = SystemClock.uptimeMillis();
2479             if (uptimeMillis >= deadlineMillis) {
2480                 break;
2481             }
2482             Slog.i(TAG_CAR, "waitForCarServiceConnection: " + (deadlineMillis - uptimeMillis));
2483             mLock.wait(deadlineMillis - uptimeMillis);
2484             Slog.i(TAG_CAR, "after waitForCarServiceConnection");
2485         }
2486     }
2487 
waitForCarServiceReady(long waitTimeoutMs)2488     private @Nullable IBinder waitForCarServiceReady(long waitTimeoutMs) {
2489         if (waitTimeoutMs == 0) {
2490             return null;
2491         }
2492 
2493         long deadlineMillis = SystemClock.uptimeMillis() + waitTimeoutMs;
2494         synchronized (mLock) {
2495             IBinder serviceBinder;
2496 
2497             while (true) {
2498                 mWaiting = true;
2499                 try {
2500                     if (waitTimeoutMs < 0) {
2501                         waitForCarServiceBinderNoTimeoutLocked();
2502                     } else {
2503                         long currentUptimeMillis = SystemClock.uptimeMillis();
2504                         if (currentUptimeMillis >= deadlineMillis) {
2505                             // Cannot get car service binder before timeout.
2506                             return null;
2507                         }
2508                         waitForCarServiceBinderLocked(deadlineMillis - currentUptimeMillis);
2509                     }
2510                     serviceBinder = mCarServiceBinder;
2511                 } catch (InterruptedException e) {
2512                     Slog.e(TAG_CAR, "Interrupted while waiting for car_service");
2513                     Thread.currentThread().interrupt();
2514                     return null;
2515                 } finally {
2516                     mWaiting = false;
2517                 }
2518                 if (serviceBinder == null) {
2519                     // Cannot get car service binder before timeout.
2520                     return null;
2521                 }
2522                 if (!setCarServiceLocked(serviceBinder)) {
2523                     Slog.e(TAG_CAR, "we got the car service binder but it is already dead, "
2524                             + "continue waiting");
2525                     mCarServiceBinder = null;
2526                 } else {
2527                     return serviceBinder;
2528                 }
2529             }
2530         }
2531     }
2532 
setCarService(IBinder carServiceBinder)2533     private boolean setCarService(IBinder carServiceBinder) {
2534         synchronized (mLock) {
2535             return setCarServiceLocked(carServiceBinder);
2536         }
2537     }
2538 
2539     // Tries to set the carServiceBinder if the service binder is valid and still alive.
2540     @GuardedBy("mLock")
setCarServiceLocked(IBinder carServiceBinder)2541     private boolean setCarServiceLocked(IBinder carServiceBinder) {
2542         ICar newService = ICar.Stub.asInterface(carServiceBinder);
2543         if (newService == null) {
2544             Slogf.wtf(TAG_CAR, "null binder service", new RuntimeException());
2545             return false;  // should not happen.
2546         }
2547         try {
2548             carServiceBinder.linkToDeath(mDeathRecipient, /* flags= */ 0);
2549         } catch (RemoteException e) {
2550             // If the binder is already dead, do not set mService. Returning an already-dead
2551             // binder to client is not useful.
2552             Slog.e(TAG_CAR, "Failed to call linkToDeath on car service binder, the binder is"
2553                     + " already dead", e);
2554             return false;
2555         }
2556         mConnectionState = STATE_CONNECTED;
2557         mService = newService;
2558         return true;
2559     }
2560 
notifyCarReady(IBinder serviceBinder)2561     private void notifyCarReady(IBinder serviceBinder) {
2562         if (mStatusChangeCallback != null) {
2563             mStatusChangeCallback.onLifecycleChanged(/* car= */ this, /* ready= */ true);
2564         } else if (mServiceConnectionListenerClient != null) {
2565             mServiceConnectionListenerClient.onServiceConnected(
2566                     new ComponentName(CAR_SERVICE_PACKAGE, CAR_SERVICE_CLASS), serviceBinder);
2567         }
2568     }
2569 
notifyCarDisconnected()2570     private void notifyCarDisconnected() {
2571         Slog.i(TAG_CAR, "notify car service disconnected");
2572         if (mStatusChangeCallback != null) {
2573             mStatusChangeCallback.onLifecycleChanged(Car.this, /* ready= */ false);
2574         } else if (mServiceConnectionListenerClient != null) {
2575             mServiceConnectionListenerClient.onServiceDisconnected(
2576                     new ComponentName(CAR_SERVICE_PACKAGE, CAR_SERVICE_CLASS));
2577         } else {
2578             // This client does not handle car service restart, so should be terminated.
2579             finishClient();
2580         }
2581     }
2582 
isMainThread()2583     private static boolean isMainThread() {
2584         return Looper.myLooper() == Looper.getMainLooper();
2585     }
2586 
assertNonNullContext(Context context)2587     private static void assertNonNullContext(Context context) {
2588         Objects.requireNonNull(context);
2589         if (context instanceof ContextWrapper
2590                 && ((ContextWrapper) context).getBaseContext() == null) {
2591             throw new NullPointerException(
2592                     "ContextWrapper with null base passed as Context, forgot to set base Context?");
2593         }
2594     }
2595 
dispatchToMainThread(boolean isMainThread, Runnable runnable)2596     private void dispatchToMainThread(boolean isMainThread, Runnable runnable) {
2597         if (isMainThread) {
2598             runnable.run();
2599         } else {
2600             // should dispatch to main thread.
2601             mMainThreadEventHandler.post(runnable);
2602         }
2603     }
2604 
notifyCarReadyOnMainThread(IBinder serviceBinder)2605     private void notifyCarReadyOnMainThread(IBinder serviceBinder) {
2606         dispatchToMainThread(isMainThread(), () -> notifyCarReady(serviceBinder));
2607     }
2608 
dispatchCarReadyToMainThread(boolean isMainThread)2609     private void dispatchCarReadyToMainThread(boolean isMainThread) {
2610         dispatchToMainThread(isMainThread,
2611                 () -> mStatusChangeCallback.onLifecycleChanged(/* car= */ this, /* ready= */ true));
2612     }
2613 
setBinderAndNotifyReady(IBinder binder)2614     private void setBinderAndNotifyReady(IBinder binder) {
2615         if (!setCarService(binder)) {
2616             Slogf.e(TAG_CAR, "the car service binder object received via onRegistration is already "
2617                     + "dead, ignore the binder");
2618             return;
2619         }
2620         Slog.i(TAG_CAR, "car_service ready on main thread, Time between Car object creation"
2621                 + " and car_service connected (ms): " + timeSinceCreateMillis());
2622         notifyCarReady(binder);
2623     }
2624 
Car(Context context, @Nullable ICar service, @Nullable ServiceConnection serviceConnectionListener, @Nullable CarServiceLifecycleListener statusChangeListener, @Nullable Handler handler, Deps deps)2625     private Car(Context context, @Nullable ICar service,
2626             @Nullable ServiceConnection serviceConnectionListener,
2627             @Nullable CarServiceLifecycleListener statusChangeListener,
2628             @Nullable Handler handler, Deps deps) {
2629         mDeps = deps;
2630         mCreateUptimeMillis = SystemClock.uptimeMillis();
2631         mContext = context;
2632         mEventHandler = determineEventHandler(handler);
2633         mMainThreadEventHandler = determineMainThreadEventHandler(mEventHandler);
2634 
2635         mService = service;
2636         if (service != null) {
2637             mConnectionState = STATE_CONNECTED;
2638         } else {
2639             mConnectionState = STATE_DISCONNECTED;
2640         }
2641         mServiceConnectionListenerClient = serviceConnectionListener;
2642         mStatusChangeCallback = statusChangeListener;
2643         // Store construction stack so that client can get help when it crashes when car service
2644         // crashes.
2645         if (serviceConnectionListener == null && statusChangeListener == null) {
2646             mConstructionStack = new RuntimeException();
2647         } else {
2648             mConstructionStack = null;
2649         }
2650     }
2651 
2652     /**
2653      * Car constructor when ICar binder is already available. The binder can be null.
2654      * @hide
2655      */
Car(Context context, @Nullable ICar service, @Nullable Handler handler)2656     public Car(Context context, @Nullable ICar service, @Nullable Handler handler) {
2657         this(context, service, null /*serviceConnectionListener*/, null /*statusChangeListener*/,
2658                 handler, SYSTEM_DEPS);
2659     }
2660 
determineMainThreadEventHandler(Handler eventHandler)2661     private static Handler determineMainThreadEventHandler(Handler eventHandler) {
2662         Looper mainLooper = Looper.getMainLooper();
2663         return (eventHandler.getLooper() == mainLooper) ? eventHandler : new Handler(mainLooper);
2664     }
2665 
determineEventHandler(@ullable Handler eventHandler)2666     private static Handler determineEventHandler(@Nullable Handler eventHandler) {
2667         Handler handler = eventHandler;
2668 
2669         if (handler == null) {
2670             Looper looper = Looper.getMainLooper();
2671             handler = new Handler(looper);
2672         }
2673         return handler;
2674     }
2675 
2676     /**
2677      * @deprecated this method is not need if this object is created via
2678      * {@link #createCar(Context, Handler)}.
2679      */
2680     @Deprecated
connect()2681     public void connect() throws IllegalStateException {
2682         IBinder carServiceBinder = null;
2683         synchronized (mLock) {
2684             if (mConnectionState != STATE_DISCONNECTED) {
2685                 throw new IllegalStateException("already connected or connecting");
2686             }
2687             mClientRequestDisconnect = false;
2688             mConnectionState = STATE_CONNECTING;
2689             if (!Flags.createCarUseNotifications()) {
2690                 // Ideally this should not be inside the lock, but legacy logic run this inside
2691                 // the lock.
2692                 startCarService();
2693                 return;
2694             }
2695 
2696             carServiceBinder = mCarServiceBinder;
2697         }
2698 
2699         if (carServiceBinder != null) {
2700             // If we already have a car service binder ready. This means this is a reconnect
2701             // after disconnect or car service crash. And car service is already ready
2702             // before connecting.
2703 
2704             // Need this to make carServiceBinder final.
2705             IBinder binder = carServiceBinder;
2706             dispatchToMainThread(isMainThread(), () -> setBinderAndNotifyReady(binder));
2707         }
2708         registerServiceListenerIfNotRegistered();
2709     }
2710 
2711     @GuardedBy("mLock")
handleCarDisconnectLocked()2712     private void handleCarDisconnectLocked() {
2713         if (mConnectionState == STATE_DISCONNECTED) {
2714             // can happen when client calls disconnect with onServiceDisconnected already
2715             // called.
2716             return;
2717         }
2718         mEventHandler.removeCallbacks(mConnectionRetryRunnable);
2719         mMainThreadEventHandler.removeCallbacks(mConnectionRetryFailedRunnable);
2720         mConnectionRetryCount = 0;
2721         tearDownCarManagersLocked();
2722         mService = null;
2723         mConnectionState = STATE_DISCONNECTED;
2724     }
2725 
2726     /**
2727      * Disconnect from car service. This can be called while disconnected. Once disconnect is
2728      * called, all Car*Managers from this instance become invalid, and
2729      * {@link Car#getCarManager(String)} or {@link Car#getCarManager(Class<T>)} will return a
2730      * different instance if it is connected again.
2731      */
disconnect()2732     public void disconnect() {
2733         synchronized (mLock) {
2734             mClientRequestDisconnect = true;
2735             handleCarDisconnectLocked();
2736             if (mServiceBound) {
2737                 mContext.unbindService(mServiceConnectionListener);
2738                 mServiceBound = false;
2739             }
2740         }
2741     }
2742 
2743     @Override
2744     @SuppressWarnings("GenericException")
finalize()2745     protected void finalize() throws Throwable {
2746         if (mLock == null) {
2747             // There's no point of trying anything - even logging - when the object state is already
2748             // cleared
2749             super.finalize();
2750             return;
2751         }
2752         try {
2753             Slog.v(TAG_CAR, "Calling disconnect() on finalize()");
2754             disconnect();
2755         } finally {
2756             super.finalize();
2757         }
2758     }
2759 
2760     /**
2761      * Tells if it is connected to the service or not. This will return false if it is still
2762      * connecting.
2763      * @return {@code true} if service is connected
2764      */
isConnected()2765     public boolean isConnected() {
2766         synchronized (mLock) {
2767             return mService != null;
2768         }
2769     }
2770 
2771     /**
2772      * Tells if this instance is already connecting to car service or not.
2773      * @return {@code true} if instance is connecting to a service
2774      */
isConnecting()2775     public boolean isConnecting() {
2776         synchronized (mLock) {
2777             return mConnectionState == STATE_CONNECTING;
2778         }
2779     }
2780 
2781     /** @hide */
2782     @VisibleForTesting
getServiceConnectionListener()2783     public ServiceConnection getServiceConnectionListener() {
2784         return mServiceConnectionListener;
2785     }
2786 
2787     /**
2788      * Get car specific service manager as in {@link Context#getSystemService(String)}. Returned
2789      * {@link Object} should be type-casted to the desired service manager.
2790      *
2791      * <p>For example, to get the manager for sensor service,
2792      * <code>
2793      * CarSensorManager carSensorManager = (CarSensorManager) car.getCarManager(Car.SENSOR_SERVICE);
2794      * </code>
2795      *
2796      * <p>For getting {@link Car#AUDIO_SERVICE}, this call might be blocked on car audio service
2797      * initialization if the client calls this early during the boot process.
2798      *
2799      * @param serviceName Name of service that should be created like {@link #SENSOR_SERVICE}.
2800      * @return Matching service manager or null if there is no such service.
2801      */
2802     @Nullable
getCarManager(String serviceName)2803     public Object getCarManager(String serviceName) {
2804         CarManagerBase manager;
2805         synchronized (mLock) {
2806             if (mService == null) {
2807                 Slog.w(TAG_CAR, "getCarManager not working while car service not ready");
2808                 return null;
2809             }
2810             manager = mServiceMap.get(serviceName);
2811             if (manager == null) {
2812                 try {
2813                     IBinder binder = mService.getCarService(serviceName);
2814                     if (binder == null) {
2815                         Slog.w(TAG_CAR, "getCarManager could not get binder for service:"
2816                                 + serviceName);
2817                         return null;
2818                     }
2819                     manager = createCarManagerLocked(serviceName, binder);
2820                     if (manager == null) {
2821                         Slog.w(TAG_CAR, "getCarManager could not create manager for service:"
2822                                         + serviceName);
2823                         return null;
2824                     }
2825                     mServiceMap.put(serviceName, manager);
2826                 } catch (RemoteException e) {
2827                     handleRemoteExceptionFromCarService(e);
2828                 }
2829             }
2830         }
2831         return manager;
2832     }
2833 
2834     /**
2835      * Get car specific service manager by class as in {@link Context#getSystemService(Class<T>)}.
2836      * Returns the desired service. No type casting is needed.
2837      *
2838      * <p>For example, to get the manager for sensor service,
2839      * <code>CarSensorManager carSensorManager = car.getCarManager(CarSensorManager.class);</code>
2840      *
2841      * <p>For getting {@link CarAudioManager}, this call might be blocked on car audio service
2842      * initialization if the client calls this early during the boot process.
2843      *
2844      * @param serviceClass The class of the desired service.
2845      * @return Matching service manager or {@code null} if there is no such service.
2846      */
2847     @Nullable
getCarManager(@onNull Class<T> serviceClass)2848     public <T> T getCarManager(@NonNull Class<T> serviceClass) {
2849         String serviceName = CAR_SERVICE_NAMES.get(serviceClass);
2850         return serviceName != null ? (T) getCarManager(serviceName) : null;
2851     }
2852 
2853     /**
2854      * @return the type of currently connected car.
2855      *
2856      * @deprecated connection type will be always {@link #CONNECTION_TYPE_EMBEDDED}
2857      */
2858     @ConnectionType
2859     @Deprecated
getCarConnectionType()2860     public int getCarConnectionType() {
2861         return CONNECTION_TYPE_EMBEDDED;
2862     }
2863 
2864     /**
2865      * Checks if {@code featureName} is enabled in this car.
2866      *
2867      * <p>For optional features, this can return false if the car cannot support it. Optional
2868      * features should be used only when they are supported.</p>
2869      *
2870      * <p>For mandatory features, this will always return true.
2871      */
isFeatureEnabled(@onNull String featureName)2872     public boolean isFeatureEnabled(@NonNull String featureName) {
2873         ICar service;
2874         synchronized (mLock) {
2875             if (mService == null) {
2876                 return false;
2877             }
2878             service = mService;
2879         }
2880         return mFeatures.isFeatureEnabled(service, featureName);
2881     }
2882 
2883     /**
2884      * Enables the requested car feature. It becomes no-op if the feature is already enabled. The
2885      * change take effects after reboot.
2886      *
2887      * @return true if the feature is enabled or was enabled before.
2888      *
2889      * @hide
2890      */
2891     @SystemApi
2892     @RequiresPermission(PERMISSION_CONTROL_CAR_FEATURES)
2893     @FeaturerRequestEnum
enableFeature(@onNull String featureName)2894     public int enableFeature(@NonNull String featureName) {
2895         ICar service;
2896         synchronized (mLock) {
2897             if (mService == null) {
2898                 return FEATURE_REQUEST_NOT_EXISTING;
2899             }
2900             service = mService;
2901         }
2902         try {
2903             return service.enableFeature(featureName);
2904         } catch (RemoteException e) {
2905             return handleRemoteExceptionFromCarService(e, FEATURE_REQUEST_NOT_EXISTING);
2906         }
2907     }
2908 
2909     /**
2910      * Disables the requested car feature. It becomes no-op if the feature is already disabled. The
2911      * change take effects after reboot.
2912      *
2913      * @return true if the request succeeds or if it was already disabled.
2914      *
2915      * @hide
2916      */
2917     @SystemApi
2918     @RequiresPermission(PERMISSION_CONTROL_CAR_FEATURES)
2919     @FeaturerRequestEnum
disableFeature(@onNull String featureName)2920     public int disableFeature(@NonNull String featureName) {
2921         ICar service;
2922         synchronized (mLock) {
2923             if (mService == null) {
2924                 return FEATURE_REQUEST_NOT_EXISTING;
2925             }
2926             service = mService;
2927         }
2928         try {
2929             return service.disableFeature(featureName);
2930         } catch (RemoteException e) {
2931             return handleRemoteExceptionFromCarService(e, FEATURE_REQUEST_NOT_EXISTING);
2932         }
2933     }
2934 
2935     /**
2936      * Returns all =enabled features at the moment including mandatory, optional, and
2937      * experimental features.
2938      *
2939      * @hide
2940      */
2941     @SystemApi
2942     @RequiresPermission(PERMISSION_CONTROL_CAR_FEATURES)
getAllEnabledFeatures()2943     @NonNull public List<String> getAllEnabledFeatures() {
2944         ICar service;
2945         synchronized (mLock) {
2946             if (mService == null) {
2947                 return Collections.EMPTY_LIST;
2948             }
2949             service = mService;
2950         }
2951         try {
2952             return service.getAllEnabledFeatures();
2953         } catch (RemoteException e) {
2954             return handleRemoteExceptionFromCarService(e, Collections.EMPTY_LIST);
2955         }
2956     }
2957 
2958     /**
2959      * Returns the list of disabled features which are not effective yet. Those features will be
2960      * disabled when system restarts later.
2961      *
2962      * @hide
2963      */
2964     @SystemApi
2965     @RequiresPermission(PERMISSION_CONTROL_CAR_FEATURES)
getAllPendingDisabledFeatures()2966     @NonNull public List<String> getAllPendingDisabledFeatures() {
2967         ICar service;
2968         synchronized (mLock) {
2969             if (mService == null) {
2970                 return Collections.EMPTY_LIST;
2971             }
2972             service = mService;
2973         }
2974         try {
2975             return service.getAllPendingDisabledFeatures();
2976         } catch (RemoteException e) {
2977             return handleRemoteExceptionFromCarService(e, Collections.EMPTY_LIST);
2978         }
2979     }
2980 
2981     /**
2982      * Returns the list of enabled features which are not effective yet. Those features will be
2983      * enabled when system restarts later.
2984      *
2985      * @hide
2986      */
2987     @SystemApi
2988     @RequiresPermission(PERMISSION_CONTROL_CAR_FEATURES)
getAllPendingEnabledFeatures()2989     @NonNull public List<String> getAllPendingEnabledFeatures() {
2990         ICar service;
2991         synchronized (mLock) {
2992             if (mService == null) {
2993                 return Collections.EMPTY_LIST;
2994             }
2995             service = mService;
2996         }
2997         try {
2998             return service.getAllPendingEnabledFeatures();
2999         } catch (RemoteException e) {
3000             return handleRemoteExceptionFromCarService(e, Collections.EMPTY_LIST);
3001         }
3002     }
3003 
3004     /** @hide */
3005     @VisibleForHiddenApiCheck
getContext()3006     public Context getContext() {
3007         return mContext;
3008     }
3009 
3010     /** @hide */
3011     @VisibleForTesting
getEventHandler()3012     public Handler getEventHandler() {
3013         return mEventHandler;
3014     }
3015 
3016     /** @hide */
3017     @VisibleForTesting
handleRemoteExceptionFromCarService(RemoteException e, T returnValue)3018     public <T> T handleRemoteExceptionFromCarService(RemoteException e, T returnValue) {
3019         handleRemoteExceptionFromCarService(e);
3020         return returnValue;
3021     }
3022 
3023     /** @hide */
3024     @VisibleForHiddenApiCheck
handleRemoteExceptionFromCarService(RemoteException e)3025     public void handleRemoteExceptionFromCarService(RemoteException e) {
3026         if (e instanceof TransactionTooLargeException) {
3027             Slog.w(TAG_CAR, "Car service threw TransactionTooLargeException", e);
3028             throw new CarTransactionException(e, "Car service threw TransactionTooLargeException");
3029         } else {
3030             Slog.w(TAG_CAR, "Car service has crashed", e);
3031         }
3032     }
3033 
finishClient()3034     private void finishClient() {
3035         if (mContext == null) {
3036             throw new IllegalStateException("Car service has crashed, null Context");
3037         }
3038         if (mContext instanceof Activity) {
3039             Activity activity = (Activity) mContext;
3040             if (!activity.isFinishing()) {
3041                 Slog.w(TAG_CAR,
3042                         "Car service crashed, client not handling it, finish Activity, created "
3043                                 + "from " + mConstructionStack);
3044                 activity.finish();
3045             }
3046             return;
3047         } else if (mContext instanceof Service) {
3048             Service service = (Service) mContext;
3049             killClient(service.getPackageName() + "," + service.getClass().getSimpleName());
3050         } else {
3051             killClient(/* clientInfo= */ null);
3052         }
3053     }
3054 
killClient(@ullable String clientInfo)3055     private void killClient(@Nullable String clientInfo) {
3056         Slog.w(TAG_CAR, "**Car service has crashed. Client(" + clientInfo + ") is not handling it."
3057                         + " Client should use Car.createCar(..., CarServiceLifecycleListener, .."
3058                         + ".) to handle it properly. Check printed callstack to check where other "
3059                         + "version of Car.createCar() was called. Killing the client process**",
3060                 mConstructionStack);
3061         mDeps.process().killProcess(mDeps.process().myPid());
3062     }
3063 
3064     /** @hide */
3065     @VisibleForHiddenApiCheck
handleRemoteExceptionFromCarService(Service service, RemoteException e, T returnValue)3066     public static <T> T handleRemoteExceptionFromCarService(Service service, RemoteException e,
3067             T returnValue) {
3068         handleRemoteExceptionFromCarService(service, e);
3069         return returnValue;
3070     }
3071 
3072     /** @hide */
3073     @VisibleForHiddenApiCheck
handleRemoteExceptionFromCarService(Service service, RemoteException e)3074     public static  void handleRemoteExceptionFromCarService(Service service, RemoteException e) {
3075         if (e instanceof TransactionTooLargeException) {
3076             Slog.w(TAG_CAR, "Car service threw TransactionTooLargeException, client:"
3077                     + service.getPackageName() + ","
3078                     + service.getClass().getSimpleName(), e);
3079             throw new CarTransactionException(e, "Car service threw TransactionTooLargeException, "
3080                 + "client: %s, %s", service.getPackageName(), service.getClass().getSimpleName());
3081         } else {
3082             Slog.w(TAG_CAR, "Car service has crashed, client:"
3083                     + service.getPackageName() + ","
3084                     + service.getClass().getSimpleName(), e);
3085             service.stopSelf();
3086         }
3087     }
3088 
3089     @Nullable
createCarManagerLocked(String serviceName, IBinder binder)3090     private CarManagerBase createCarManagerLocked(String serviceName, IBinder binder) {
3091         CarManagerBase manager = null;
3092         switch (serviceName) {
3093             case AUDIO_SERVICE:
3094                 manager = new CarAudioManager(this, binder);
3095                 break;
3096             case SENSOR_SERVICE:
3097                 manager = new CarSensorManager(this, binder);
3098                 break;
3099             case INFO_SERVICE:
3100                 manager = new CarInfoManager(this, binder);
3101                 break;
3102             case APP_FOCUS_SERVICE:
3103                 manager = new CarAppFocusManager(this, binder);
3104                 break;
3105             case PACKAGE_SERVICE:
3106                 manager = new CarPackageManager(this, binder);
3107                 break;
3108             case CAR_OCCUPANT_ZONE_SERVICE:
3109                 manager = new CarOccupantZoneManager(this, binder);
3110                 break;
3111             case CAR_NAVIGATION_SERVICE:
3112                 manager = new CarNavigationStatusManager(this, binder);
3113                 break;
3114             case CABIN_SERVICE:
3115                 manager = new CarCabinManager(this, binder);
3116                 break;
3117             case DIAGNOSTIC_SERVICE:
3118                 manager = new CarDiagnosticManager(this, binder);
3119                 break;
3120             case HVAC_SERVICE:
3121                 manager = new CarHvacManager(this, binder);
3122                 break;
3123             case POWER_SERVICE:
3124                 manager = new CarPowerManager(this, binder);
3125                 break;
3126             case PROJECTION_SERVICE:
3127                 manager = new CarProjectionManager(this, binder);
3128                 break;
3129             case PROPERTY_SERVICE:
3130                 manager = new CarPropertyManager(this, ICarProperty.Stub.asInterface(binder));
3131                 break;
3132             case VENDOR_EXTENSION_SERVICE:
3133                 manager = new CarVendorExtensionManager(this, binder);
3134                 break;
3135             case CAR_INSTRUMENT_CLUSTER_SERVICE:
3136                 manager = new CarInstrumentClusterManager(this, binder);
3137                 break;
3138             case TEST_SERVICE:
3139                 /* CarTestManager exist in static library. So instead of constructing it here,
3140                  * only pass binder wrapper so that CarTestManager can be constructed outside. */
3141                 manager = new CarTestManager(this, binder);
3142                 break;
3143             case VEHICLE_MAP_SERVICE:
3144                 manager = new VmsClientManager(this, binder);
3145                 break;
3146             case VMS_SUBSCRIBER_SERVICE:
3147                 manager = VmsSubscriberManager.wrap(this,
3148                         (VmsClientManager) getCarManager(VEHICLE_MAP_SERVICE));
3149                 break;
3150             case STORAGE_MONITORING_SERVICE:
3151                 manager = new CarStorageMonitoringManager(this, binder);
3152                 break;
3153             case CAR_DRIVING_STATE_SERVICE:
3154                 manager = new CarDrivingStateManager(this, binder);
3155                 break;
3156             case CAR_UX_RESTRICTION_SERVICE:
3157                 manager = new CarUxRestrictionsManager(this, binder);
3158                 break;
3159             case OCCUPANT_AWARENESS_SERVICE:
3160                 manager = new OccupantAwarenessManager(this, binder);
3161                 break;
3162             case CAR_MEDIA_SERVICE:
3163                 manager = new CarMediaManager(this, binder);
3164                 break;
3165             case CAR_BUGREPORT_SERVICE:
3166                 manager = new CarBugreportManager(this, binder);
3167                 break;
3168             case CAR_USER_SERVICE:
3169                 manager = new CarUserManager(this, binder);
3170                 break;
3171             case CAR_WATCHDOG_SERVICE:
3172                 manager = new CarWatchdogManager(this, binder);
3173                 break;
3174             case CAR_INPUT_SERVICE:
3175                 manager = new CarInputManager(this, binder);
3176                 break;
3177             case CAR_DEVICE_POLICY_SERVICE:
3178                 manager = new CarDevicePolicyManager(this, binder);
3179                 break;
3180             case CLUSTER_HOME_SERVICE:
3181                 manager = new ClusterHomeManager(this, binder);
3182                 break;
3183             case CAR_EVS_SERVICE:
3184                 manager = new CarEvsManager(this, binder, /* featureFlags= */ null);
3185                 break;
3186             case CAR_TELEMETRY_SERVICE:
3187                 manager = new CarTelemetryManager(this, binder);
3188                 break;
3189             case CAR_ACTIVITY_SERVICE:
3190                 manager = new CarActivityManager(this, binder);
3191                 break;
3192             case CAR_PERFORMANCE_SERVICE:
3193                 manager = new CarPerformanceManager(this, binder);
3194                 break;
3195             case CAR_REMOTE_ACCESS_SERVICE:
3196                 manager = new CarRemoteAccessManager(this, binder);
3197                 break;
3198             case CAR_OCCUPANT_CONNECTION_SERVICE:
3199                 manager = new CarOccupantConnectionManager(this, binder);
3200                 break;
3201             case CAR_REMOTE_DEVICE_SERVICE:
3202                 manager = new CarRemoteDeviceManager(this, binder);
3203                 break;
3204             default:
3205                 // Experimental or non-existing
3206                 if (Flags.displayCompatibility()) {
3207                     if (serviceName.equals(CAR_DISPLAY_COMPAT_SERVICE)) {
3208                         manager =  new CarDisplayCompatManager(this, binder);
3209                         break;
3210                     }
3211                 }
3212                 if (Flags.persistApSettings()) {
3213                     if (serviceName.equals(CAR_WIFI_SERVICE)) {
3214                         manager = new CarWifiManager(this, binder);
3215                         break;
3216                     }
3217                 }
3218                 if (Flags.carPropertySimulation()) {
3219                     if (serviceName.equals(CAR_PROPERTY_SIMULATION_SERVICE)) {
3220                         manager = new CarPropertySimulationManager(this, binder);
3221                         break;
3222                     }
3223                 }
3224                 String className = null;
3225                 try {
3226                     synchronized (mLock) {
3227                         className = mService.getCarManagerClassForFeature(serviceName);
3228                     }
3229                 } catch (RemoteException e) {
3230                     handleRemoteExceptionFromCarService(e);
3231                     return null;
3232                 }
3233                 if (className == null) {
3234                     Slog.e(TAG_CAR, "Cannot construct CarManager for service:" + serviceName
3235                             + " : no class defined");
3236                     return null;
3237                 }
3238                 manager = constructCarManager(className, binder);
3239                 break;
3240         }
3241         return manager;
3242     }
3243 
constructCarManager(String className, IBinder binder)3244     private CarManagerBase constructCarManager(String className, IBinder binder) {
3245         try {
3246             // Should use class loader for the Context as class loader for car api does not
3247             // see the class.
3248             ClassLoader loader = mContext.getClassLoader();
3249             Class managerClass = loader.loadClass(className);
3250             Constructor constructor = managerClass.getConstructor(Car.class, IBinder.class);
3251             CarManagerBase manager = (CarManagerBase) constructor.newInstance(this, binder);
3252             return manager;
3253         } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException
3254                 | InstantiationException | InvocationTargetException e) {
3255             Slog.e(TAG_CAR, "Cannot construct CarManager, class:" + className, e);
3256             return null;
3257         }
3258     }
3259 
startCarService()3260     private void startCarService() {
3261         Intent intent = new Intent();
3262         intent.setPackage(CAR_SERVICE_PACKAGE);
3263         intent.setAction(Car.CAR_SERVICE_INTERFACE_NAME);
3264         boolean bound = mContext.bindService(intent, mServiceConnectionListener,
3265                 Context.BIND_AUTO_CREATE);
3266         synchronized (mLock) {
3267             if (!bound) {
3268                 mConnectionRetryCount++;
3269                 if (mConnectionRetryCount > mDeps.carServiceBindMaxRetry()) {
3270                     Slog.w(TAG_CAR, "cannot bind to car service after max retry");
3271                     mMainThreadEventHandler.post(mConnectionRetryFailedRunnable);
3272                 } else {
3273                     mEventHandler.postDelayed(mConnectionRetryRunnable,
3274                             mDeps.carServiceBindRetryIntervalMs());
3275                 }
3276             } else {
3277                 mEventHandler.removeCallbacks(mConnectionRetryRunnable);
3278                 mMainThreadEventHandler.removeCallbacks(mConnectionRetryFailedRunnable);
3279                 mConnectionRetryCount = 0;
3280                 mServiceBound = true;
3281             }
3282         }
3283     }
3284 
3285     @GuardedBy("mLock")
tearDownCarManagersLocked()3286     private void tearDownCarManagersLocked() {
3287         // All disconnected handling should be only doing its internal cleanup.
3288         for (CarManagerBase manager : mServiceMap.values()) {
3289             manager.onCarDisconnected();
3290         }
3291         mServiceMap.clear();
3292     }
3293 }
3294