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