CarContext

public class CarContext
extends ContextWrapper

java.lang.Object
   ↳ android.content.Context
     ↳ android.content.ContextWrapper
       ↳ androidx.car.app.CarContext


The CarContext class is a ContextWrapper subclass accessible to your CarAppService and Screen instances, which provides access to car services such as the ScreenManager for managing the screen stack, the AppManager for general app-related functionality such as accessing a surface for drawing your navigation app's map, and the NavigationManager used by turn-by-turn navigation apps to communicate navigation metadata and other navigation-related events with the host. See Access the navigation templates for a comprehensive list of library functionality available to navigation apps.

Whenever you use a CarContext to load resources, the following configuration elements come from the car screen's configuration, and not the phone:

  • Screen width.
  • Screen height.
  • Screen pixel density (DPI).
  • Night mode (See isDarkMode()).

Please refer here, on how to use configuration qualifiers in your resources.

Summary

Constants

String ACTION_NAVIGATE

Standard action for navigating to a location.

String APP_SERVICE

Manages all app events such as invalidating the UI, showing a toast, etc.

String CAR_SERVICE

Internal usage only.

String CONSTRAINT_SERVICE

Manages constraints for the app as enforced by the connected host.

String EXTRA_START_CAR_APP_BINDER_KEY

Key for including a IStartCarApp in the notification Intent, for starting the app if it has not been opened yet.

String HARDWARE_SERVICE

Manages access to androidx.car.app.hardware properties, sensors and actions.

String NAVIGATION_SERVICE

Manages all navigation events such as starting navigation when focus is granted, abandoning navigation when focus is lost, etc.

String SCREEN_SERVICE

Manages the screens of the app, including the screen stack.

Inherited constants

Public methods

void finishCarApp()

Requests to finish the car app.

ComponentName getCallingComponent()

Return the component (service or activity) that invoked this car app.

int getCarAppApiLevel()

Retrieves the API level negotiated with the host.

<T extends Manager> T getCarService(Class<T> serviceClass)

Returns the a car service, by class.

Object getCarService(String name)

Provides a car service by name.

String getCarServiceName(Class<? extends Manager> serviceClass)

Gets the name of the car service that is represented by the specified class.

HostInfo getHostInfo()

Returns information about the host attached to this service.

OnBackPressedDispatcher getOnBackPressedDispatcher()

Returns the OnBackPressedDispatcher that will be triggered when the user clicks a back button.

boolean isDarkMode()

Returns true if the car is set to dark mode.

void requestPermissions(List<String> permissions, OnRequestPermissionsListener listener)

Requests the provided permissions from the user, calling the provided listener in the main thread.

void requestPermissions(List<String> permissions, Executor executor, OnRequestPermissionsListener listener)

Requests the provided permissions from the user.

void setCarAppResult(int resultCode, Intent data)

Sets the result of this car app.

void startCarApp(Intent intent)

Starts a car app on the car screen.

static void startCarApp(Intent notificationIntent, Intent appIntent)

This method is deprecated. use CarPendingIntent.getCarApp(Context, int, Intent, int) to create the pending intent for the notification action. This API will NOT work for Automotive OS.

Inherited methods

Constants

ACTION_NAVIGATE

public static final String ACTION_NAVIGATE

Standard action for navigating to a location.

Used as the Intent's action for starting a navigation via startCarApp(Intent).

Constant Value: "androidx.car.app.action.NAVIGATE"

APP_SERVICE

public static final String APP_SERVICE

Manages all app events such as invalidating the UI, showing a toast, etc.

Constant Value: "app"

CAR_SERVICE

public static final String CAR_SERVICE

Internal usage only. Top level binder to host.

Constant Value: "car"

CONSTRAINT_SERVICE

public static final String CONSTRAINT_SERVICE

Manages constraints for the app as enforced by the connected host.

Constant Value: "constraints"

EXTRA_START_CAR_APP_BINDER_KEY

public static final String EXTRA_START_CAR_APP_BINDER_KEY

Key for including a IStartCarApp in the notification Intent, for starting the app if it has not been opened yet.

Constant Value: "androidx.car.app.extra.START_CAR_APP_BINDER_KEY"

HARDWARE_SERVICE

public static final String HARDWARE_SERVICE

Manages access to androidx.car.app.hardware properties, sensors and actions.

Constant Value: "hardware"

public static final String NAVIGATION_SERVICE

Manages all navigation events such as starting navigation when focus is granted, abandoning navigation when focus is lost, etc.

Constant Value: "navigation"

SCREEN_SERVICE

public static final String SCREEN_SERVICE

Manages the screens of the app, including the screen stack.

Constant Value: "screen"

Public methods

finishCarApp

public void finishCarApp ()

Requests to finish the car app.

Call this when your app is done and should be closed. The Session corresponding to this CarContext will become State.DESTROYED.

At some point after this call, the OS will destroy your CarAppService.

This method should not be called until the Lifecycle.State of the context's Session is at least Lifecycle.State.CREATED.

getCallingComponent

public ComponentName getCallingComponent ()

Return the component (service or activity) that invoked this car app.

This is who the data in setCarAppResult(int, Intent) will be sent to. You can use this information to validate that the recipient is allowed to receive the data.

Starting applications for result is not implemented in Android Auto, and this method will always return null for that platform.

Returns
ComponentName the ComponentName of the component that will receive your reply, or null if none

getCarAppApiLevel

public int getCarAppApiLevel ()

Retrieves the API level negotiated with the host.

API levels are used during client and host connection handshake to negotiate a common set of elements that both processes can understand. Different devices might have different host versions. Each of these hosts will support a range of API levels, as a way to provide backwards compatibility.

Applications can also provide forward compatibility, by declaring support for a AppInfo.getMinCarAppApiLevel() lower than AppInfo.getLatestCarAppApiLevel(). See AppInfo.getMinCarAppApiLevel() for more details.

Clients must ensure no elements annotated with a RequiresCarApi value higher than returned by this method is used at runtime.

Refer to RequiresCarApi description for more details on how to implement forward compatibility.

This method should not be called until the Lifecycle.State of the context's Session is at least Lifecycle.State.CREATED.

Returns
int a value between AppInfo.getMinCarAppApiLevel() and AppInfo.getLatestCarAppApiLevel(). In case of incompatibility, the host will disconnect from the service before completing the handshake

Throws
IllegalStateException if invoked before the connection handshake with the host has been completed (for example, before Session.onCreateScreen(Intent))

getCarService

public T getCarService (Class<T> serviceClass)

Returns the a car service, by class.

Currently supported classes are: AppManager, NavigationManager, ScreenManager.

This method should not be called until the Lifecycle.State of the context's Session is at least Lifecycle.State.CREATED.

Parameters
serviceClass Class: the class of the requested service

Returns
T

Throws
IllegalArgumentException if serviceClass is not the class of a supported car service
IllegalStateException if serviceClass can not be instantiated (e.g. missing library dependency)
NullPointerException if serviceClass is null

getCarService

public Object getCarService (String name)

Provides a car service by name.

The class of the returned object varies by the requested name.

Currently supported car services, and their respective classes, are:

APP_SERVICE
An AppManager for communication between the app and the host.
NAVIGATION_SERVICE
A NavigationManager for management of navigation updates.
SCREEN_SERVICE
A ScreenManager for management of Screens.

This method should not be called until the Lifecycle.State of the context's Session is at least Lifecycle.State.CREATED.

Parameters
name String: The name of the car service requested. This should be one of APP_SERVICE, NAVIGATION_SERVICE or SCREEN_SERVICE

Returns
Object The car service instance

Throws
IllegalArgumentException if name does not refer to a valid car service
IllegalStateException if the service referred by name can not be instantiated (e.g. missing library dependency)
NullPointerException if name is null

getCarServiceName

public String getCarServiceName (Class<? extends Manager> serviceClass)

Gets the name of the car service that is represented by the specified class.

This method should not be called until the Lifecycle.State of the context's Session is at least Lifecycle.State.CREATED.

Parameters
serviceClass Class: the class of the requested service

Returns
String the car service name to use with getCarService(String)

Throws
IllegalArgumentException if serviceClass is not the class of a supported car service
NullPointerException if serviceClass is null

getHostInfo

public HostInfo getHostInfo ()

Returns information about the host attached to this service.

Returns
HostInfo The HostInfo of the connected host, or null if it is not available.

See also:

getOnBackPressedDispatcher

public OnBackPressedDispatcher getOnBackPressedDispatcher ()

Returns the OnBackPressedDispatcher that will be triggered when the user clicks a back button.

The default back press behavior is to call ScreenManager.pop().

To override the default behavior, register a OnBackPressedCallback via calling OnBackPressedDispatcher.addCallback(LifecycleOwner, OnBackPressedCallback). Using the LifecycleOwner ensures that your callback is only registered while its Lifecycle is at least Lifecycle.State.STARTED.

If there is a OnBackPressedCallback that is added and enabled, and you'd like to remove the top Screen as a part of the callback, you MUST call ScreenManager.pop() in the callback. The default behavior is overridden when you have a callback enabled.

Returns
OnBackPressedDispatcher

isDarkMode

public boolean isDarkMode ()

Returns true if the car is set to dark mode.

Navigation applications must redraw their map with the proper dark colors when the host determines that conditions warrant it, as signaled by the value returned by this method.

Whenever the dark mode status changes, you will receive a call to Session.onCarConfigurationChanged(Configuration).

This method should not be called until the Lifecycle.State of the context's Session is at least Lifecycle.State.CREATED.

Returns
boolean

requestPermissions

public void requestPermissions (List<String> permissions, 
                OnRequestPermissionsListener listener)

Requests the provided permissions from the user, calling the provided listener in the main thread.

Parameters
permissions List

listener OnRequestPermissionsListener

requestPermissions

public void requestPermissions (List<String> permissions, 
                Executor executor, 
                OnRequestPermissionsListener listener)

Requests the provided permissions from the user.

When the result is available, the listener provided will be called using the Executor provided.

This method should be called using a ParkedOnlyOnClickListener.

If this method is called while the host deems it is unsafe (for example, when the user is driving), the permission(s) will not be requested from the user.

If the Session is destroyed before the user accepts or rejects the permissions, the callback will not be executed.

Platform Considerations

Using this method allows the app to work across all platforms supported by the library with the same API (e.g. Android Auto on mobile devices and Android Automotive OS on native car heads unit). On a mobile platform, this method will start an activity that will display the platform's permissions UI over it. You can choose to not use this method and instead implement your own activity and code to request the permissions in that platform. On Automotive OS however, distraction-optimized activities other than CarAppActivity are not allowed and may be rejected during app submission. See CarAppActivity for more details.

Parameters
permissions List: the runtime permissions to request from the user

executor Executor: the executor that will be used for calling the callback provided

listener OnRequestPermissionsListener: listener that will be notified when the user takes action on the permission request

Throws
NullPointerException if any of executor, permissions or callback are null

setCarAppResult

public void setCarAppResult (int resultCode, 
                Intent data)

Sets the result of this car app.

In Android Automotive OS, this is equivalent to Activity.setResult(int, Intent). Call this to set the result that your CarAppActivity will return to its caller.

This method is not implemented in Android Auto.

Parameters
resultCode int: the result code to propagate back to the originating app, often Activity.RESULT_CANCELED or Activity.RESULT_OK

data Intent: the data to propagate back to the originating app

Throws
IllegalStateException if the method is not supported in the current platform.

startCarApp

public void startCarApp (Intent intent)

Starts a car app on the car screen.

The target application will get the Intent via Session.onCreateScreen(Intent) or Session.onNewIntent(Intent).

Supported Intents:

An Intent to navigate.
The action must be ACTION_NAVIGATE.
The data URI scheme must be either a latitude,longitude pair, or a + separated string query as follows:
1) "geo:12.345,14.8767" for a latitude, longitude pair.
2) "geo:0,0?q=123+Main+St,+Seattle,+WA+98101" for an address.
3) "geo:0,0?q=a+place+name" for a place to search for.
An Intent to make a phone call.
The Intent must be created as defined here.
An Intent to start this app in the car.
The component name of the intent must be the one for the CarAppService that contains this CarContext. If the component name is for a different component, the method will throw a SecurityException.

This method should not be called until the Lifecycle.State of the context's Session is at least Lifecycle.State.CREATED.

Parameters
intent Intent: the Intent to send to the target application

Throws
SecurityException if the app attempts to start a different app explicitly or does not have permissions for the requested action
HostException if the remote call fails
NullPointerException if intent is null

startCarApp

public static void startCarApp (Intent notificationIntent, 
                Intent appIntent)

This method is deprecated.
use CarPendingIntent.getCarApp(Context, int, Intent, int) to create the pending intent for the notification action. This API will NOT work for Automotive OS.

Starts the car app on the car screen.

Use this method if the app has received a broadcast due to a notification action.

Parameters
notificationIntent Intent: the Intent that the app received via broadcast due to a user taking an action on a notification in the car

appIntent Intent: the Intent to use for starting the car app. See startCarApp(Intent) for the documentation on valid Intents

Throws
InvalidParameterException if notificationIntent is not an Intent received from a broadcast, due to an action taken by the user in the car
NullPointerException if either notificationIntent or appIntent are null