Add Android Automotive OS support to your media app

Android Automotive OS lets users install apps in the car. To reach users on this platform, you need to distribute a driver-optimized app that is compatible with Android Automotive OS. You can reuse almost all the code and resources in your Android Auto app, but you must create a separate build that meets the requirements on this page.

Development overview

Adding Android Automotive OS support only requires a few steps, as described in the sections that follow:

  1. Enable automotive features in Android Studio.
  2. Create an automotive module.
  3. Update your Gradle dependencies.
  4. Optionally, Implement settings and sign-in activities.
  5. Optionally, Read media host hints.

Design considerations

Android Automotive OS takes care of laying out the media content that it receives from your app's media browser service. This means that your app doesn't draw the UI and doesn't start any of your activities when a user triggers media playback.

If you are implementing settings or sign-in activities, these activities must be vehicle-optimized. Refer to the Design guidelines for Android Automotive OS while designing those areas of your app.

Set up your project

You need to set up several parts of your app's project to enable support for Android Automotive OS.

Enable automotive features in Android Studio

Use Android Studio 4.0 or higher to ensure that all Automotive OS features are enabled.

Create an automotive module

Some components of Android Automotive OS, such as the manifest, have platform-specific requirements. Create a module that can keep the code for these components separate from other code in your project, such as the code used for your phone app.

Follow these steps to add an automotive module to your project:

  1. In Android Studio, click File > New > New Module.
  2. Select Automotive Module, then click Next.
  3. Enter an Application/Library name. This is the name that users see for your app on Android Automotive OS.
  4. Enter a Module name.
  5. Adjust the Package name to match your app.
  6. Select API 28: Android 9.0 (Pie) for the Minimum SDK, and then click Next.

    All cars that support Android Automotive OS run on Android 9 (API level 28) or higher, so selecting this value targets all compatible cars.

  7. Select No Activity, and then click Finish.

After creating your module in Android Studio, open the AndroidManifest.xml in your new automotive module:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.media">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" />

    <uses-feature
        android:name="android.hardware.type.automotive"
        android:required="true" />

</manifest>

The application element has some standard app information as well as a uses-feature element that declares support for Android Automotive OS. Note that there are no activities declared in the manifest.

If you implement settings or sign-in activities, add them here. These activities are triggered by the system using explicit intents and are the only activities you declare within the manifest for your Android Automotive OS app.

After adding any settings or sign-in activities, complete your manifest file by setting the android:appCategory="audio" attribute in the application element and adding the following uses-feature elements:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.media">

    <application
        android:allowBackup="true"
        android:appCategory="audio"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" />

    <uses-feature
        android:name="android.hardware.type.automotive"
        android:required="true" />

    <uses-feature
        android:name="android.hardware.wifi"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.screen.portrait"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.screen.landscape"
        android:required="false" />

</manifest>

Explicitly setting these features to required="false" ensures that your app doesn't conflict with available hardware features in Automotive OS devices.

Declare media support for Android Automotive OS

Use the following manifest entry to declare that your app supports Android Automotive OS:

<application>
    ...
    <meta-data android:name="com.android.automotive"
        android:resource="@xml/automotive_app_desc"/>
    ...
</application>

This manifest entry refers to an XML file that declares the automotive capabilities that your app supports.

To indicate that you have a media app, add an XML file named automotive_app_desc.xml to the res/xml/ directory in your project. Include the following content in this file:

<automotiveApp>
    <uses name="media"/>
</automotiveApp>

Intent filters

Android Automotive OS uses explicit intents to trigger activities in your media app. Don't include any activities that have CATEGORY_LAUNCHER or ACTION_MAIN intent filters in the manifest file.

Activities like the one in the following example usually target a phone or some other mobile device. Declare these activities in the module that builds the phone app, not in the module that builds your Android Automotive OS app.

<activity android:name=".MyActivity">
    <intent-filter>
        <!-- You can't use either of these intents for Android Automotive OS -->
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <!--
        In their place, you can include other intent filters for any activities
        that your app needs for Android Automotive OS, such as settings or
        sign-in activities.
        -->
    </intent-filter>
</activity>

Update your Gradle dependencies

We recommend that you keep your media browser service in a separate module that you share between your phone app and your automotive module. If you're using this approach, you need to update your automotive module to include the shared module, as shown in the following snippet:

my-auto-module/build.gradle

Groovy

buildscript {
    ...
    dependencies {
        ...
        implementation project(':shared_module_name')
    }
}

Kotlin

buildscript {
    ...
    dependencies {
        ...
        implementation(project(":shared_module_name"))
    }
}

Implement settings and sign-in activities

In addition to your media browser service, you can also provide vehicle-optimized settings and sign-in activities for your Android Automotive OS app. These activities let you provide app functionality that isn't included in the Android Media APIs.

Only implement these activities if your Android Automotive OS app needs to let users sign in or specify app settings. These activities aren't used by Android Auto.

Activity workflows

The following diagram shows how a user interacts with your settings and sign-in activities using Android Automotive OS:

Workflows for Settings and Sign-in activities

Figure 1. Settings and sign-in activity workflows.

Discourage distractions in your settings and sign-in activities

To ensure your settings and/or sign-in activities are only available for use while the user's vehicle is parked, verify that the <activity> element(s) don't include the following <meta-data> element. Your app will be rejected during review if such an element is present.

<!-- NOT ALLOWED -->
<meta-data
  android:name="distractionOptimized"
  android:value="true"/>

Add a settings activity

You can add a vehicle-optimized settings activity so that users can configure settings for your app in their car. Your settings activity can also provide other workflows, like signing in or out of a user's account or switching user accounts. Remember that this activity is only triggered by an app running on Android Automotive OS. Phone apps connected to Android Auto do not use it.

Declare a settings activity

You must declare your settings activity in your app's manifest file, as shown in the following code snippet:

<application>
    ...
    <activity android:name=".AppSettingsActivity"
              android:exported="true"
              android:theme="@style/SettingsActivity"
              android:label="@string/app_settings_activity_title">
        <intent-filter>
            <action android:name="android.intent.action.APPLICATION_PREFERENCES"/>
        </intent-filter>
    </activity>
    ...
</application>

Implement your settings activity

When a user launches your app, Android Automotive OS detects the settings activity that you declared and displays an affordance, such as an icon. The user can tap or select this affordance using their car's display to navigate to the activity. Android Automotive OS sends the ACTION_APPLICATION_PREFERENCES intent that tells your app to start your settings activity.

The rest of this section shows how you can adapt code from the Universal Android Music Player (UAMP) sample app to implement a settings activity for your app.

To begin, download the sample code:

# Clone the UAMP repository
git clone https://github.com/android/uamp.git

# Fetch the appropriate pull request to your local repository
git fetch origin pull/323/head:NEW_LOCAL_BRANCH_NAME

# Switch to the new branch
git checkout NEW_LOCAL_BRANCH_NAME

To implement your activity, follow these steps:

  1. Copy the automotive/automotive-lib folder into your automotive module.
  2. Define a preferences tree as in automotive/src/main/res/xml/preferences.xml.
  3. Implement a PreferenceFragmentCompat that your settings activity displays. See the SettingsFragment.kt and SettingsActivity.kt files in UAMP and the Android Settings guide for more information.

As you implement your settings activity, consider these best practices for using some of the components in the Preference library:

  • Have no more than two levels of depth below the main view in your settings activity.
  • Don't use a DropDownPreference. Use a ListPreference instead.
  • Organizational components:
  • Include a key and title in all the following components. You can also include a summary, an icon, or both:
    • Preference
      • Customize the logic in the onPreferenceTreeClick() callback of your PreferenceFragmentCompat implementation.
    • CheckBoxPreference
      • Can have summaryOn or summaryOff instead of summary for conditional text.
    • SwitchPreference
      • Can have summaryOn or summaryOff instead of summary for conditional text.
      • Can have switchTextOn or switchTextOff.
    • SeekBarPreference
      • Include a min, max, and defaultValue.
    • EditTextPreference
      • Include dialogTitle, positiveButtonText, and negativeButtonText.
      • Can have dialogMessage and/or dialogLayoutResource.
    • com.example.android.uamp.automotive.lib.ListPreference
      • Derives mostly from ListPreference.
      • Used to display a single-choice list of Preference objects.
      • Must have an array of entries and corresponding entryValues.
    • com.example.android.uamp.automotive.lib.MultiSelectListPreference
      • Derives mostly from MultiSelectListPreference
      • Used to display a multiple-choice list of Preference objects.
      • Must have an array of entries and corresponding entryValues.

Add a sign-in activity

If your app requires a user to sign in before they can use your app, you can add a vehicle-optimized sign-in activity that handles signing in and out of your app. You can also add sign-in and sign-out workflows to a settings activity, but use a dedicated sign-in activity if your app can't be used until a user signs in. Remember that this activity is only triggered by an app running on Android Automotive OS. Phone apps connected to Android Auto do not use it.

Require sign in at app start

To require a user to sign in before they can use your app, your media browser service must do the following things:

  1. In your service's onLoadChildren() method, send null result using the sendResult() method.
  2. Set the media session's PlaybackStateCompat to STATE_ERROR using the setState() method. This tells Android Automotive OS that no other operations can be performed until the error has been resolved.
  3. Set the media session's PlaybackStateCompat error code to ERROR_CODE_AUTHENTICATION_EXPIRED. This tells Android Automotive OS that the user needs to authenticate.
  4. Set the media session's PlaybackStateCompat error message using the setErrorMessage() method. Because this error message is user-facing, localize it for the user's current locale.
  5. Set the media session's PlaybackStateCompat extras using the setExtras() method. Include the following two keys:

The following code snippet shows how your app can require the user to sign in before using your app:

Kotlin

import androidx.media.utils.MediaConstants

val signInIntent = Intent(this, SignInActivity::class.java)
val signInActivityPendingIntent = PendingIntent.getActivity(this, 0,
    signInIntent, 0)
val extras = Bundle().apply {
    putString(
        MediaConstants.PLAYBACK_STATE_EXTRAS_KEY_ERROR_RESOLUTION_ACTION_LABEL,
        "Sign in"
    )
    putParcelable(
        MediaConstants.PLAYBACK_STATE_EXTRAS_KEY_ERROR_RESOLUTION_ACTION_INTENT,
        signInActivityPendingIntent
    )
}

val playbackState = PlaybackStateCompat.Builder()
        .setState(PlaybackStateCompat.STATE_ERROR, 0, 0f)
        .setErrorMessage(
            PlaybackStateCompat.ERROR_CODE_AUTHENTICATION_EXPIRED,
            "Authentication required"
        )
        .setExtras(extras)
        .build()
mediaSession.setPlaybackState(playbackState)

Java

import androidx.media.utils.MediaConstants;

Intent signInIntent = new Intent(this, SignInActivity.class);
PendingIntent signInActivityPendingIntent = PendingIntent.getActivity(this, 0,
    signInIntent, 0);
Bundle extras = new Bundle();
extras.putString(
    MediaConstants.PLAYBACK_STATE_EXTRAS_KEY_ERROR_RESOLUTION_ACTION_LABEL,
    "Sign in");
extras.putParcelable(
    MediaConstants.PLAYBACK_STATE_EXTRAS_KEY_ERROR_RESOLUTION_ACTION_INTENT,
    signInActivityPendingIntent);

PlaybackStateCompat playbackState = new PlaybackStateCompat.Builder()
    .setState(PlaybackStateCompat.STATE_ERROR, 0, 0f)
    .setErrorMessage(
            PlaybackStateCompat.ERROR_CODE_AUTHENTICATION_EXPIRED,
            "Authentication required"
    )
    .setExtras(extras)
    .build();
mediaSession.setPlaybackState(playbackState);

After the user is successfully authenticated, set the PlaybackStateCompat back to a state other than STATE_ERROR, then take the user back to Android Automotive OS by calling the activity's finish() method.

Implement your sign-in activity

Google offers a variety of identity tools that you can use to help users sign in to your app in their cars. Some tools, such as Firebase Authentication, provide full-stack toolkits that can help you build customized authentication experiences. Other tools leverage a user's existing credentials or other technologies to help you build seamless sign-in experiences for users.

The following tools can help you build an easier sign-in experience for users who have previously signed in on another device:

  • One Tap Sign-in and Sign-up: if you already implemented One Tap for other devices, such as your phone app, implement it for your Android Automotive OS app to support existing One Tap users.
  • Google Sign-in: if you already implemented Google Sign-in for other devices, such as your phone app, implement Google Sign-in for your Android Automotive OS app to support existing Google Sign-in users.
  • Autofill with Google: if users have opted into Autofill with Google on their other Android devices, their credentials are saved to the Google password manager. When those users sign in to your Android Automotive OS app, Autofill with Google suggests relevant saved credentials. Using Autofill with Google requires no application development effort. However, application developers can optimize their apps for better quality results. Autofill with Google is supported by all devices running Android 8.0 (API level 26) or higher, including Android Automotive OS.

Use AccountManager

Android Automotive OS apps that have authentication must use AccountManager, for the following reasons:

  • Better UX and ease of account management: users can easily manage all their accounts from the accounts menu in the system settings, including sign-in and sign-out.
  • "Guest" experiences: cars are shared devices, which means OEMs can enable "guest" experiences in the vehicle, where accounts cannot be added. This restriction is achieved using DISALLOW_MODIFY_ACCOUNTS for AccountManager.

Permissions

If you need to request permissions from the user, use the same flow as the authentication activity or the settings activity in the activity workflows diagram shown in a previous section.

Read media host hints

Depending on the system application (including its version) that connects to your media browser service, your application may receive the following extras:

Error Handling

Errors in media apps on Android Automotive OS are communicated via the media session’s PlaybackStateCompat. For all errors, set an appropriate error code and error message in the PlaybackStateCompat. This causes a Toast to appear in the UI.

When an error occurs but playback can continue, issue a non-fatal error. For example, a user might be able to play music in an app before signing in, but they must sign in before they can skip a song. When you use a non-fatal error, the system can suggest that the user log in without interrupting playback for the current media item.

When you issue a non-fatal error, preserve the rest of the PlaybackStateCompat as-is, aside from the error code and error message. Using this approach lets playback for the current media item to continue while the user decides whether to sign in.

When playback is not possible, such as when there is no internet connection and no offline content, set the PlaybackStateCompat state to STATE_ERROR.

On subsequent updates to your PlaybackStateCompat, clear any error codes and error messages to avoid displaying multiple warnings for the same error.

If at any point you are unable to load a browse tree—for example, if you require authentication and the user is not signed in—send an empty browse tree. To signify this, return a null result from onLoadChildren() for the root media node. When this happens, the system displays a full-screen error with the error message set in the PlaybackStateCompat.

Actionable errors

If an error is actionable, additionally set the following two extras in the PlaybackStateCompat:

Actionable errors appear as a Dialog and can resolved by users only when the car is stopped.

Testing error cases

Verify that your app gracefully handles errors in all scenarios, including:

  • Different tiers of your product: for example, free versus premium or signed in versus signed out
  • Different drive states: for example, parked versus driving
  • Different connectivity states: for example, online versus offline

Other considerations

Keep these other considerations in mind when developing your Android Automotive OS app:

Offline content

If applicable, implement offline playback support. Cars with Android Automotive OS are expected to have their own data connectivity, meaning a data plan is included in the cost of the vehicle or paid for by the user. However, cars are also expected to have more variable connectivity than mobile devices.

Here are a few things to keep in mind as you consider your offline support strategy:

  • The best time to download content is while your app is in use.
  • Do not assume that WiFi is available. A car might never come into WiFi range, or the OEM might have disabled WiFi in favor of a cellular network.
  • While it is okay to smartly cache the content expect users to use, we recommend that you let the user change this behavior through your settings activity.
  • The disk space on cars varies, so give users a way to delete offline content, such as through an option in your settings activity.

WebView support

WebViews are supported in Android Automotive OS but are only allowed for your settings and sign-in activities. Activities that use a WebView must have a "close" or "back" affordance outside of the WebView.

Here are some examples of acceptable use-cases for WebViews:

  • Displaying your privacy policy, terms of service, or other legal-related links in your settings activity.
  • A web-based flow in your sign-in activity.

When using a WebView, you can enable Javascript.

Secure your WebView

Take all precautions possible to help ensure that your WebView is not an entry point into the greater internet. See the following code snippet for an example on how to lock the WebView to the URL used in the loadUrl() call and prevent redirects. We highly recommend that you implement safeguards like this when feasible, such as when displaying legal-related links.

Kotlin

override fun shouldOverrideUrlLoading(webView: WebView,
                             webResourceRequest: WebResourceRequest): Boolean {
  val originalUri: Uri = Uri.parse(webView.originalUrl)
  // Check for allowed URLs
  if (originalUri.equals(Uri.parse(BLANK_URL))
      || originalUri.equals(webResourceRequest.url)) {
    return false
  }
  if (webResourceRequest.isRedirect) {
    logger.w("Redirect detected, not following")
    return true
  }
  setupWizardWebViewClientListener.onUriBlocked(webResourceRequest.url)
  logger.w(
    String.format(
      "Navigation prevented to %s original is %s", webResourceRequest.url, originalUri))
  return true
}

Java

@Override
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
  Uri originalUri = Uri.parse(webView.getOriginalUrl());
  // Check for allowed URLs
  if (originalUri.equals(Uri.parse(BLANK_URL))
      || originalUri.equals(webResourceRequest.getUrl())) {
    return false;
  }
  if (webResourceRequest.isRedirect()) {
    logger.w("Redirect detected, not following");
    return true;
  }
  setupWizardWebViewClientListener.onUriBlocked(webResourceRequest.getUrl());
  logger.w(
      String.format(
          "Navigation prevented to %s original is %s", webResourceRequest.getUrl(), originalUri));
  return true;
}

Package names

Because you distribute a separate Android Package Kit (APK) for Android Automotive OS, you can reuse the package name from your mobile app or create a new package name. If you use a different package name, your app has two separate Play Store listings. If you reuse your current package name, your app has a single listing across both platforms.

This is predominantly a business decision. For example, if you have one team working on the mobile app, and a separate team working on your Android Automotive OS app, then it might make sense to have separate package names and let each team manage its own Play Store listing. There is not a large difference in the technical effort required to use either approach.

The following table summarizes some other key differences between keeping your current package name and using a new package name:

Feature Same package name New package name
Store listing Single Multiple
Mirrored install Yes: “fast app reinstall” during the setup wizard No
Play Store Review process Blocking reviews: if the review fails for one APK, other APKs submitted in the same release are blocked Individual reviews
Statistics, metrics, and vitals Combined: you can filter for automotive-specific data. Separate
Indexing and search ranking Build off current standing No carryover
Integrating with other apps Most likely no changes needed, assuming media code is shared between both APKs Might have to update the corresponding app, such as for URI playback with Google Assistant.

Frequently asked questions

See the following sections for answers to some frequently asked questions about Android Automotive OS.

Hardware

Can my app get access to the microphone

For apps targeting Android 10 (API level 29) or higher, refer to the sharing audio input documentation. This is not feasible prior to API level 29.

Which car APIs can we get access to and how?

You are limited to the APIs that are exposed by the OEM. Processes are being developed to standardize how you access these APIs.

Apps can access car APIs using SetProperty() and GetProperty() in CarPropertyManager. Refer to the source code or reference documentation to see a list of all available properties. If the property is annotated with @SystemApi, it is limited to preloaded system apps.

What types of audio codecs are supported?

Refer to the audio codec details in the Android CDD.

Is Widevine DRM supported?

Yes. Widevine DRM is supported.

Development and testing

Are there any restrictions or recommendations for using third-party SDKs and libraries?

We don’t have any specific guidelines on using third-party SDKs and libraries. If you choose to use third-party SDKs and libraries, you are still responsible for complying with all the car app quality requirements.

Can I use a foreground service?

The only allowed use-case for a foreground service is downloading content for offline use. If you have another use-case for a foreground service that you want to see support for, get in touch with us using the Android Automotive OS discussion group.

Publishing Android Automotive OS apps

How do I publish my Android Automotive OS app using the Google Play Console?

The app publishing process is similar to publishing a phone app, but you use a different form factor. To opt in your app to use the Android Automotive OS form factor, follow these steps:

  1. Open the Play Console.
  2. Select your app.
  3. From the left menu, click Release > Setup > Advanced settings > Form factors.
  4. Click Add form factor > Android Automotive OS, then follow the instructions in the Play Console.

Additional resources

To learn more about Android Automotive OS, see the following additional resources.

Samples

Guides

Blogs

Videos

Report an Android Automotive OS Media issue

If you run into an issue while developing your media app for Android Automotive OS, you can report it using the Google Issue Tracker. Be sure to fill out all the requested information in the issue template.

Create a new issue

Before filing a new issue, check whether it is already reported in the issues list. You can subscribe and vote for issues by clicking the star for an issue in the tracker. For more information, see Subscribing to an Issue.