Update News

***TOP NEWS * How to delete google search? Give the offer GOOGLE

Monday 16 March 2015

Getting Started with Auto

Getting Started with Auto

DEPENDENCIES AND PREREQUISITES

  • Android 5.0 (API level 21) or higher

THIS CLASS TEACHES YOU HOW TO

  1. Set Up an Auto Project
  2. Build Auto Apps
  3. Run and Test Auto Apps

YOU SHOULD ALSO READ

  • Designing for Auto
  • Providing Audio Playback with Auto
  • Providing Messaging for Auto
Android Auto extends the Android platform into the car. When users connect their handheld devices running Android 5.0 or higher to a compatible vehicle, the Auto user interface provides a car-optimized Android experience on the vehicle's screen. Users interact with compatible apps and services through voice actions and the vehicle's input controls (like a touchscreen or dashboard buttons).
Auto currently supports two types of apps:
  • Audio apps that allow users to browse and play music and spoken audio content in the car.
  • Messaging apps that receive incoming notifications, read messages aloud via text-to-speech, and send replies via voice input in the car.
You can enable your existing audio and messaging apps developed for phones and tablets to work in the car, without having to worry about vehicle-specific hardware differences. To enable your app for Auto, your app must target Android 5.0 (API level 21) or higher. Your app’s manifest must also declare the car capabilities that it uses, such as audio playback or messaging services.
This lesson describes how to start building apps for Auto, including setting up your development environment and meeting the the minimum requirements to enable an app to communicate with Auto.
Important: If you are planning to develop apps for Auto, you are encouraged to begin enabling and testing your apps now. However, Auto-enabled apps cannot be published at this time. Join the Auto Developers Google+ community for updates on when you will be able to submit your Auto-enabled apps.

Set Up an Auto Project


This section describes how to create a new app or modify an existing app to communicate with Auto.

Prerequisites

Before you begin building apps for Auto, you must:
  • Create or update your app project - Android 5.0 (API level 21) provides new APIs for implementing audio playback and messaging that is compatible with Auto. To access the new APIs, create a project or modify an existing project to target Android 5.0 (API level 21) or higher. This means you must set the manifesttargetSdkVersion to 21 or higher.
  • Install the support library - If you are building messaging apps for Auto, you need theNotificationCompat.CarExtender class contained in the v4 support library. This class allows you to create notifications that are compatible with Auto devices.

Declare Auto capabilities

The Auto features that your app can access are controlled by the settings in your app manifest and a separate XML configuration file. Before adding Auto features to your app, you must first define the Auto XML configuration file and add a manifest entry referencing your XML file.

Define the Auto XML configuration file

Specify the car capabilities that your app uses in an XML file that you place in your project’s resources directory (res/xml/). For example, to extend an audio application for Auto, create a file called automotive_app_desc.xmland store it under your projects’s res/xml/ folder. The automotive_app_desc.xml file contains the following metadata:
<automotiveApp>
   <uses name="media" />
</automotiveApp>
The <uses> element declares the Auto capability your app intends to use. Multiple <uses> tags can be added if your application uses multiple car capabilities. The name attribute indicates the specific capability your app uses. The values supported are:
  • media - The app uses the Android framework APIs to play music in a vehicle. Set this value if you are enabling an audio app for Auto.
  • notification - The app displays message notifications in the car’s Overview screen, allows users select a message to be read aloud, and lets them respond through voice input. Set this value if you are enabling a messaging app for Auto.

Add a manifest entry

In your app’s manifest (AndroidManifest.xml), provide a reference to the Auto XML configuration file you created in the previous section. Add a "com.google.android.gms.car.application" metadata entry under the<application> element that references your Auto XML configuration file. Omit the .xml file extension when specifying the configuration filename.
The following code snippet shows how to include this reference in your manifest.
<application>

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

Add Auto Features to Your Apps


After you have completed the steps described above, you're ready to add Auto features to your apps. See these additional topics to help you build apps for Auto:
  • Providing Audio Playback for Auto - Create apps that let users browse and play music in the car.
  • Providing Messaging for Auto - Enable users to receive and reply to messages in the car.
Important: Google takes driver distraction very seriously. There are specific design requirements your app must meet to qualify as an Auto app on Google Play. By adhering to these requirements, you can reduce the effort for building and testing your app. For more information, see Auto App Quality.

Run and Test Auto Apps


As you prepare to publish your app, make sure that your app looks correct when projected on the Auto user interface. Use the Android Media Browser simulator and Android Messaging simulators to view and test your audio or messaging apps in a screen that looks similar to what is projected on Auto.
To get the simulators, open the SDK Manager and download them from Extras > Android Auto API Simulators.
Before you begin testing, compile your app in your development environment. Install your app and the Android simulator for the features you want to test (that is, audio or messaging) on a physical or virtual device running Android 5.0 (API level 21) or higher. To check the version of Android on the device, go to Settings > About > Android Version.

Testing audio apps

To run and test audio apps:
  1. Install the Android Media Browser simulator (<sdk>/extras/google/simulators/media-browser-simulator.apk) on the test device. You can do this using the adb command line tool.
  2. Enable developer options on the test device.
  3. Install your app on the test device.
  4. Launch the Android Media Browser simulator to see how your audio app appears in Auto. If your app does not appear, stop the simulator from Settings > Apps then restart it.

Testing messaging apps

To run and test messaging apps:
  1. Install the Android Messaging simulator (<sdk>/extras/google/simulators/messaging-simulator.apk) on the test device. You can do this using the adb command line tool.
  2. Enable the simulator to read notifications posted on the system:
    1. Enable developer options on the test device.
    2. Click Settings > Sounds & Notifications > Notification Access and check the box labeled Messaging Simulator.
  3. Install your app on the test device.
  4. Launch the Android Messaging Simulator to see how your messaging app appears in Auto. If your app does not appear, stop the simulator from Settings > Apps then restart it.

Providing Audio Playback for Auto

DEPENDENCIES AND PREREQUISITES

  • Android 5.0 (API level 21) or higher

THIS CLASS TEACHES YOU HOW TO

  1. Provide Audio Services
  2. Configure Your Manifest
  3. Build a Browser Service
  4. Implement Play Controls

RELATED SAMPLES

  • MediaBrowserService

SEE ALSO

  • User Experience Guidelines: Media Apps
  • Managing Audio Playback
  • ExoPlayer

VIDEO

Devbytes: Android Auto Audio

Drivers want to access their music and other audio content on the road. Audio books, podcasts, sports commentary, and recorded talks can make a long trip educational, inspirational, and enjoyable. The Android framework allows you to extend your audio app so users can listen to their favorite tunes and audio content using a simpler, safer user interface.
Apps running on mobile devices with Android 5.0 or higher can provide audio services for dashboard systems running Android Auto. By configuring your app with a few settings and implementing a service for accessing music tracks, you can enable Auto devices to discover your app and provide a browse and playback interface for your app's audio content.
This class assumes that you have built an app that plays audio through an Android device's integrated speakers or connected headphones. It describes how to extend your app to allow Auto devices to browse your content listings and play it through a car stereo system.

Provide Audio Services


Audio apps do not directly control a car dashboard device that runs Android Auto. When the user connects an Android mobile device into a dashboard system, Android Auto discovers your app through manifest entries that indicate what audio services your app can provide. The dashboard system displays a launcher icon for your app as a music provider and the user can choose to use your app's services. If the user launches your app, the Auto device queries your app to see what content is available, displays your content items to the user, and sends requests to your app to control playback with actions such as play, pause, or skip track.
To enable your app to provide audio content for Auto devices, you need to:
  • Configure your app manifest to do the following:
    • Declare that your app can provide audio content for Auto devices.
    • Define a service that provides a browsable list of your audio tracks.
  • Build a service that provides audio track listing information extending MediaBrowserService.
  • Register a MediaSession object and implement the MediaSession.Callback object to enable playback controls.

Configure Your Manifest


When a user plugs an Android mobile device into a dashboard device running Auto, the system requests a list of installed apps that include app manifest entries to indicate they support services for Auto devices and how to access them. This section describes how to configure your app manifest to indicate your app supports audio services for Auto devices, and allow dashboard system to connect with your app.

Declare Auto audio support

You indicate that your app supports cars capabilities using the following manifest entry:
<application>
    ...
    <meta-data android:name="com.google.android.gms.car.application"
        android:resource="@xml/automotive_app_desc"/>
    ...<application>
This manifest entry refers to a secondary XML file, where you declare what Auto capabilities your app supports. For an app that supports audio for cars, add an XML file to the res/xml/ resources directory asautomotive_app_desc.xml, with the following content:
<automotiveApp>
    <uses name="media"/>
</automotiveApp>
For more information about declaring capabilities for Auto devices, see Getting Started with Auto.

Declare your media browser service

Auto devices expect to connect to a service in order to browse audio track listings. You declare this service in your manifest to allow the dashboard system to discover this service and connect to your app.
The following code example shows how to declare this listing browser service in your manifest:
<application>
    ...
    <service android:name=".MyMediaBrowserService"
                android:exported="true">
        <intent-filter>
            <action android:name=
                "android.media.browse.MediaBrowserService"/>
        </intent-filter>
    </service>
    ...<application>
The service your app provides for browsing audio tracks must extend the MediaBrowserService. The implementation of this service is discussed in the Build a Browser Service section.
Note: Other clients can also contact your app's browser service aside from Auto devices. These media clients might be other apps on a user's mobile device, or they might be other remote clients.

Specify a notification icon

The Auto user interface shows notifications about your audio app to the user during the course of operation. For example, if the user has a navigation app running, and one song finishes and a new song starts, the Auto device shows the user a notification to indicate the change with an icon from your app. You can specify an icon that is used to represent your app for these notifications using the following manifest declaration:
<application>
    ...
    <meta-data android:name="com.google.android.gms.car.notification.SmallIcon"
        android:resource="@drawable/ic_notification" />
    ...<application>
Note: The icon you provide should have transparency enabled, so the icon's background gets filled in with the app's primary color.

Build a Browser Service


Auto devices interact with your app by contacting its implementation of a MediaBrowserService, which you declare in your app manifest. This service allows Auto devices to find out what content your app provides. Connected Auto devices can also query your app's media browser service to contact the MediaSession provided by your app, which handles content playback commands.
You create a media browser service by extending the MediaBrowserService class. Connected Auto devices can contact your service to do the following:
  • Browse your app's content hierarchy, in order to present a menu to the user
  • Get the token for your app's MediaSession object, in order to control audio playback

Media browser service workflow

  1. When your app's audio services are requested by a user through a connected Auto device, the dashboard system contacts your app's media browser service. In your implementation of the onCreate() method, you must create and register a MediaSession object and its callback object.
  2. The Auto device calls the browser service's onGetRoot() method to get the top node of your content hierarchy. The node retrieved by this call is not used as a menu item, it is only used to retrieve its child nodes, which are subsequently displayed as the top menu items.
  3. Auto invokes the onLoadChildren() method to get the children of the root node, and uses this information to present a menu to the user.
  4. If the user selects a submenu, Auto invokes onLoadChildren() again to retrieve the child nodes of the selected menu item.
  5. If the user begins playback, Auto invokes the appropriate media session callback method to perform that action. For more information, see the section about how to Implement Playback Controls.

Building your content hierarchy

Auto devices acting as audio clients call your app's MediaBrowserService to find out what content you have available. You need to implement two methods in your browser service to support this: onGetRoot() andonLoadChildren().
Each node in your content hierarchy is represented by a MediaBrowser.MediaItem object. Each of these objects is identified by a unique ID string. The client treats these ID strings as opaque tokens. When a client wants to browse to a submenu, or play a content item, it passes the ID token. Your app is responsible for associating the ID token with the appropriate menu node or content item.
Note: You should consider providing different content hierarchies depending on what client is making the query. In particular, Auto applications have strict limits on how large a menu they can display. This is intended to prevent distracting the driver, and to make it easy for the driver to operate the app via voice commands. For more information on the Auto user experience restrictions, see the Auto Media Apps guidelines.
Your implementation of onGetRoot() returns information about the root node of the menu hierarchy. This root node is the parent of the top items your browse hierarchy. The method is passed information about the calling client. You can use this information to decide if the client should have access to your content at all. For example, if you want to limit your app's content to a list of approved clients, you can compare the passedclientPackageName to your whitelist. If the caller isn't an approved package, you can return null to deny access to your content.
A typical implementation of onGetRoot() might look like this:
@Override
public BrowserRoot onGetRoot(String clientPackageName, int clientUid,
    Bundle rootHints) {

    // To ensure you are not allowing any arbitrary app to browse your app's
    // contents, you need to check the origin:
    if (!PackageValidator.isCallerAllowed(this, clientPackageName, clientUid)) {
        // If the request comes from an untrusted package, return null.
        // No further calls will be made to other media browsing methods.
        LogHelper.w(TAG, "OnGetRoot: IGNORING request from untrusted package "
                + clientPackageName);
        return null;
    }
    if (ANDROID_AUTO_PACKAGE_NAME.equals(clientPackageName)) {
        // Optional: if your app needs to adapt ads, music library or anything
        // else that needs to run differently when connected to the car, this
        // is where you should handle it.
    }
    return new BrowserRoot(MEDIA_ID_ROOT, null);
}
The Auto device client builds the top-level menu by calling onLoadChildren() with the root node object and getting it's children. The client builds submenus by calling the same method with other child nodes. The following example code shows a simple implementation of onLoadChildren() method:
@Override
public void onLoadChildren(final String parentMediaId,
    final Result<List<MediaItem>> result) {

    // Assume for example that the music catalog is already loaded/cached.

    List<MediaBrowser.MediaItem> mediaItems = new ArrayList<>();

    // Check if this is the root menu:
    if (MEDIA_BROWSER_ROOT.equals(parentMediaId)) {

        // build the MediaItem objects for the top level,
        // and put them in the <result> list
    } else {

        // examine the passed parentMediaId to see which submenu we're at,
        // and put the children of that menu in the <result> list
    }
}

Enable Playback Control


Auto devices use MediaSession objects to pass playback control commands to an app that is providing audio services. Your audio app must create an instance of this object to pass to the dashboard device and implement callback methods to enable remote control of audio playback.

Register a media session

An Auto device using your app as audio service needs to obtain a MediaSession object from your app. The Auto device uses the session object to send playback commands requested by the Auto user back to your app.
When you initialize your browser service, you register that session object with your MediaBrowserService by calling the setSessionToken() method. This step allows clients such as an Auto device to retrieve that object by calling your browser service's getSessionToken() method.
In your browser service's onCreate() method, create a MediaSession. You can then query the MediaSession to get its token, and register the token with your browser service:
public void onCreate() {
        super.onCreate();

    ...
    // Start a new MediaSession
    MediaSession mSession = new MediaSession(this, "session tag");
    setSessionToken(mSession.getSessionToken());

    // Set a callback object to handle play control requests, which
    // implements MediaSession.Callback
    mSession.setCallback(new MyMediaSessionCallback());

    ...
When you create the media session object, you set a callback object that is used to handle playback control requests. You create this callback object by providing an implementation of the MediaSession.Callback class for your app. The next section discusses how to implement this object.

Implement play commands

When an Auto device requests playback of an audio track from your app, it uses the MediaSession.Callbackclass from your app's MediaSession object, which it obtained from your app's media browse service. When an Auto user wants to play content or control content playback, such as pausing play or skipping to the next track, Auto invokes one of the callback object's methods.
To handle content playback, your app must extend the abstract MediaSession.Callback class and implement the methods that your app supports. The most important callback methods are as follows:
onPlay()
Invoked if the user chooses play without choosing a specific item. Your app should play its default content. If playback was paused with onPause(), your app should resume playback.
onPlayFromMediaId()
Invoked when the user chooses to play a specific item. The method is passed the item's media ID, which you assigned to the item in the content hierarchy.
onPlayFromSearch()
Invoked when the user chooses to play from a search query. The app should make an appropriate choice based on the passed search string.
onPause()
Pause playback.
onSkipToNext()
Skip to the next item.
onSkipToPrevious()
Skip to the previous item.
onStop()
Stop playback.
Your app should override these methods to provide any desired functionality. In some cases you might not implement a method if it is not supported by your app. For example, if your app plays a live stream (such as a sports broadcast), the skip to next function might not make sense. In that case, you could simply use the default implementation of onSkipToNext().
When your app receives a request to play content, it should play audio the same way it would in a non-Auto situation (as if the user was listening through a device speaker or connected headphones). The audio content is automatically sent to the dashboard system to be played over the car's speakers.
For more information about playing audio content, see Media Playback, Managing Audio Playback, andExoPlayer. (for example, by using a MediaPlayer or ExoPlayer). If the phone is connected to an Auto device, .

Providing Messaging for Auto

DEPENDENCIES AND PREREQUISITES

  • Android 5.0 (API level 21) or higher

THIS CLASS TEACHES YOU TO:

  • Provide Messaging Services
  • Configure Your Manifest
  • Import Support Library for Messaging
  • Notify Users of Messages
  • Handle User Actions

RELATED SAMPLES

  • MessagingService

SEE ALSO

  • User Experience Guidelines: Messaging Apps
  • Notifications

VIDEO

DevBytes: Android Auto Messaging

Staying connected through messages is important to many drivers. Chat apps can let users know if a child need to be picked up, or if a dinner location has been changed. Apps that provide sports information might tell the user who just won the big game, and let the user ask questions about other games being played. The Android framework enables messaging apps to extend their services into car dashboards using a standard user interface that lets drivers keep their eyes on the road.
Apps that support messaging can be extended to pass messaging notifications to Auto dashboard systems, alerting them to new messages and allowing them to respond. You can configure your messaging app to provide these services when an Android mobile device with your app installed is connected to an Auto dashboard. Once connected, your app can provide text information to users and allow them to respond. The Auto dashboard system handles displaying the notification and the interface for replies.
This lesson assumes that you have built an app that displays messages to the user and receive the user's replies, such as a chat app. It shows you how to extend your app to hand those messages off to an Auto device for display and replies.

Provide Messaging Services


Messaging apps do not run directly on the Android dashboard hardware. They are installed on separate, Android mobile device. When the mobile device is plugged into a dashboard, the installed messaging apps can offer services for viewing and responding to messages through the Auto user interface.
To enable your app to provide messaging services for Auto devices:
  • Configure your app manifest to indicate that your app provides messaging services which are compatible with Android Auto dashboard devices.
  • Build and send a specific type of notification for display on Auto devices.
  • Configure your app to receive Intent objects that indicate a user has read or replied to a message.

Concepts and Objects

Before you start designing your app, it's helpful to understand how Auto handles messaging.
Each individual chunk of communication is a message. A message is a short length of text, suitable for the Auto device to read aloud. In a chat app, this might be a single message from one person to another: "Fitzy -- Jane can't come to the ball, her youngest has the croup. :-( --Liz" In a sports app, a message might be a single bit of news about a game: "Granger scores for Harpies at 7 minutes in."
conversation is a group of messages that are all grouped together in some way. Auto uses the conversation information to group the messages together when presenting them to the user. In a chat app, a conversation might be all the messages between the user and another person (for example, all the messages back and forth between Darcy and Elizabeth). In a sports app, a conversation might be all the messages about a particular game. Every message belongs to a conversation, even if it's the only message in that conversation. Each conversation has a conversation name. The conversation name is used by Android Auto to present the messages; it's up to your app to choose an appropriate conversation name. In a chat app, the conversation name is usually the person your user is talking to. In a sports app, this might be the name of the teams playing in the game.
The v4 support library defines an UnreadConversation object. This object holds all messages in a conversation which have not yet been heard by the user. To give those messages to the user, you attach thatUnreadConversation to a notification. However, you do not attach messages to the UnreadConversation directly. Instead, you must first set up an UnreadConversation.Builder object for the conversation. The messages are added to the builder, then when you are ready to send the messages, you use the builder to create the actualUnreadConversation and attach the UnreadConversation to the notification.
Note: When Auto presents messages to the user, it uses the notification tag and ID to determine which conversation the messages belong to. It is important to use the same tag and ID for all messages in a conversation, and to not use that tag for other conversations.

Workflow

This section describes how the mobile device interacts with Auto to present messages to the user.
  1. The app receives a message that it wants to pass on to the user. It attaches the message to anUnreadConversation object and attaches it to a notification. That notification is associated with aCarExtender object, which indicates that the notification can be handled by Android Auto.
  2. The app posts the notification. The Android notification framework passes the message to Auto. Auto uses the notification tag and ID to determine which conversation the message belongs to, and presents the message to the user in an appropriate way.
  3. When the user listens to the message, Auto triggers the app's message heard pending intent. The app should discard the UnreadConversation object and its builder at this time, since the messages contained in those objects have been heard by the user.
  4. If the user sends a reply, Auto triggers the app's "message reply" intent and attaches a transcript of the user's response. The app can take appropriate action, based on the app's logic. For example, a chat app might interpret the reply as a message to go to the other conversation participants, while a sports app might try to interpret the "reply" as a request for other information ("What's the score in the Sharks game?").

Configure Your Manifest


You configure your app manifest to indicate that it supports messaging services for Auto devices and handle message actions. This section describes what changes to make to your manifest to support messaging for Auto devices.

Declare Auto messaging support

When a user connects a Android mobile device to a dashboard running Android, the dashboard device looks for apps that declare support for vehicle services, such as messaging. You indicate that your app supports cars capabilities using the following manifest entry:
<application>
    ...
    <meta-data android:name="com.google.android.gms.car.application"
        android:resource="@xml/automotive_app_desc" />
    ...<application>
This manifest entry refers to a secondary xml file, where you declare what Auto capabilities your app supports. For an app that supports messaging for Auto devices, add an xml file to the res/xml/ your app's development project directory as automotive_app_desc.xml, with the following content:
<automotiveApp>
    <uses name="notification"/>
</automotiveApp>
For more information about declaring capabilities for Auto devices, see Getting Started with Auto.

Define read and reply intent filters

Auto devices use Intent objects that indicate a user has read or replied to a message provided by your app. Your app defines intent types for reading and replying to messages and adds this information to messaging notifications for Auto devices, so that the dashboard system can notify your app when a user takes one of these actions.
You define the read action and reply action intents types for your app and the BroadcastReceiver classes that handle them in the manifest. The following code example demonstrates how to declare these intents and their associated receivers.
<application>
    ...
    <receiver android:name=".MyMessageHeardReceiver">
        <intent-filter>
          <action android:name="com.myapp.messagingservice.MY_ACTION_MESSAGE_HEARD"/>
        </intent-filter>
    </receiver>

    <receiver android:name=".MyMessageReplyReceiver">
        <intent-filter>
          <action android:name="com.myapp.messagingservice.MY_ACTION_MESSAGE_REPLY"/>
        </intent-filter>
    </receiver>
    ...</application>
In this example, "MyMessageReadReceiver" and "MyMessageReplyReceiver" are the names of theBroadcastReceiver subclasses you define to handle the intents. You can choose whatever you like as the action names, but it's best to prepend your package name to ensure that the action names are unique. For more information about handling actions, see Handle User Actions.

Import Support Library for Messaging


Building notifications for use with Auto devices requires classes from the v4 support library. Use the Android SDK Manager to update the Extras > Android Support Repository to version 9 or higher and the Extras > Android Support Library to version 21.0.2 or higher.
After you have updated the support libraries, import them into your Android Studio development project by adding this dependency to your build.gradle file:
dependencies {
    ...
    compile 'com.android.support:support-v4:21.0.2'
}
For information about importing the support library into development projects for other development environments, see Support Library Setup.

Notify Users of Messages


A messaging app provides messages to a connected Auto dashboard using the notifications framework. When your messaging app has a message for a user, you build a specially configured notification that is received by the dashboard system and presented to the user. The Auto device manages the presentation on the dashboard screen and may play the message via text-to-speech. The dashboard system also handles voice interaction if the user replies to a message using verbal input.
The messaging user interface for Auto presents users with two levels of information about messages. The first level of notification tells users what conversations are available, and who they are with, but not the content of the messages. Typically, a conversation is one or more messages from another user to the Auto user.
The second level of the notification is the actual content of messages in the conversation. If a user indicates they want to hear the messages in a conversation, the Auto user interface plays the messages using text-to-speech.
This section describes how to notify Auto users that conversations are available and provide the content of messages in those conversations.

Create conversation read and reply intents

Unread conversation objects contain intents for reading and replying to a conversation. You create aPendingIntent object for each of these actions, so the Auto device can notify your app of action taken by the Auto user on a particular conversation.
The following example code demonstrates how to define a PendingIntent to let your app know if a conversation was read to the Auto user:
Intent msgHeardIntent = new Intent()
    .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
    .setAction("com.myapp.messagingservice.MY_ACTION_MESSAGE_HEARD")
    .putExtra("conversation_id", thisConversationId);
PendingIntent msgHeardPendingIntent =
    PendingIntent.getBroadcast(getApplicationContext(),
        thisConversationId,
        msgHeardIntent,
        PendingIntent.FLAG_UPDATE_CURRENT);
In this example, thisConversationId is an integer that identifies the current conversation. The value ofIntent.setAction() is the intent filter identifier for heard messages which you defined in your app manifest, as shown in Define read and reply intent filters.
If your app supports replying to conversations, you also create a PendingIntent for each conversation to notify your app that the user has replied. The following code example shows you how to build this intent for use with a particular conversation:
Intent msgReplyIntent = new Intent()
    .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
    .setAction("com.myapp.messagingservice.MY_ACTION_MESSAGE_REPLY")
    .putExtra("conversation_id", thisConversationId);
PendingIntent msgReplyPendingIntent = PendingIntent.getBroadcast(
    getApplicationContext(),
    thisConversationId,
    msgReplyIntent,
    PendingIntent.FLAG_UPDATE_CURRENT);
Once again, thisConversationId is an integer that uniquely identifies this conversation, and the value you pass to Intent.setAction() is the intent filter identifier you defined for replies in your app manifest.

Set up the conversation builder

Messaging notifications for Auto organize messages into conversations using theNotificationCompat.CarExtender.UnreadConversation class, that represents an unread or new portion of a conversation from a particular sender. It contains a list of messages from the sender.
You generally do not configure the UnreadConversation directly. Instead, you configure anUnreadConversation.Builder with the information about the conversation, as shown in the following example code.
// Build a RemoteInput for receiving voice input in a Car Notification
RemoteInput remoteInput = new RemoteInput.Builder(MY_VOICE_REPLY_KEY)
        .setLabel(getApplicationContext().getString(R.string.notification_reply))
        .build();
// Create an unread conversation object to organize a group of messages
// from a particular sender.
UnreadConversation.Builder unreadConvBuilder =
    new UnreadConversation.Builder(conversationName)
        .setReadPendingIntent(msgHeardPendingIntent)
        .setReplyAction(msgReplyPendingIntent, remoteInput);
Note: You won't actually create the UnreadConversation until you are almost ready to send the message.
This conversation object includes a PendingIntent, which allows the Auto device to signal your app that the conversation has been read by the Auto user. The construction of this intent is discussed in the Creating conversation read and reply intents section.
If your app supports replying to a conversation, you must call theUnreadConversation.Builder.setReplyAction() method and provide a pending intent to pass that user action back to your app. The UnreadConversation object you create must also include a RemoteInput object. When the Auto user receiving this conversation speaks a reply, the remote input objects lets your app get a text version of the voice reply.

Sending Messages

When a message arrives for a conversation, you take the following steps to dispatch it as a notification to Auto.
First, add the message to the UnreadConversation.Builder for this conversation, and update its timestamp:
unreadConvBuilder.addMessage(messageString)
    .setLatestTimestamp(currentTimestamp);
Note: If you are sending several messages at once, add them to the UnreadConversation.Builder in order, from oldest to newest.
Then create the NotificationCompat.Builder object that builds the actual notification. You need to use the pending intents you created in the previous step.
NotificationCompat.Builder notificationBuilder =
    new NotificationCompat.Builder(getApplicationContext())
        .setSmallIcon(smallIconResourceID)
        .setLargeIcon(largeIconBitmap);
smallIconResourceID
The resource ID of a small icon to use for the conversation. This is typically a generic icon for the messaging app.
largeIconBitmap
Bitmap of a large version of the icon. This is typically a conversation-specific graphic. For example, if this is a chat app, the large icon would be a picture of the person the user is chatting with.
messageString
The text of the message you want to send. (If you are sending several messages at once, concatenate them into a single string, with the oldest message first.)
currentTimestamp
The message timestamp. (If you are sending several messages at once, use the timestamp of the most recent message.)
conversationName
The name you chose for this conversation (for example, the name of the person the user is chatting with). This should be the same conversation name you used when you created the UnreadConversation.Builder.
msgHeardPendingIntent
The pending intent object you created in Create conversation read and reply intents.
You'll also need to extend the NotificationCompat.Builder with the CarExtender. This is where you actually create the UnreadConversation object using the builder you just created, and attach it to the CarExtender:
notificationBuilder.extend(new CarExtender()
    .setUnreadConversation(unreadConvBuilder.build());
Note: If you wish, you can set an override icon or color for the CarExtender by calling setLargeIcon() orsetColor(). The override icon or color is used when the notification is handled by a car, and has no effect if the notification is handled on the Android device. This is useful if the notification's default icon or color are not suitable for the car's display.
Once you've done all this, you use your app's NotificationManagerCompat to send the notification:
NotificationManagerCompat msgNotificationManager =
    NotificationManagerCompat.from(context);
msgNotificationManager.notify(notificationTag,
    notificationId, notificationBuilder.build());

Handle User Actions


When your create and dispatch a notification for messaging, you specify intents to be triggered when the Auto user hears the message and when the user dictates a reply. Your app indicates to the Android framework that it handles these intends by registering them through its manifest, as discussed in Define read and reply intent filters.
In addition to registering these intent filters, your app must provide code to handle these actions. Your app can do this by providing a service or BroadcastReceiver objects that handle these intents.
For more information about intents, see Intents and Intent Filters.

Handling a message heard action

When a user listens to a messaging conversation through the Auto user interface, the dashboard device sends a read intent based on how your app defined the messaging notification. Your app catches that intent and invokes the broadcast receiver class associated with it, or the service method set up to handle that action.
The following code example shows how to define a BroadcastReceiver class to handle a received message heard intent:
public class MyMessageHeardReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // If you set up the intent as described in
        // "Create conversation read and reply intents",
        // you can get the conversation ID by calling:
        int thisConversationId = intent.getIntExtra("conversation_id", -1);

        // Remove the notification to indicate it has been read
        // and update the list of unread conversations in your app.
    }
}
Once a notification is read, your app can remove it by calling NotificationManagerCompat.cancel() with the notification ID. Within your app, you should mark the messages provided in the notification as read.
Note: An alternative to this implementation is to use a service in a PendingIntent.

Handling a reply action

When a user replies to a messaging conversation through the Auto user interface, the dashboard system sends a reply intent based on how your app defined the messaging notification. Your app catches that intent and invokes the broadcast receiver class associated with it, or the service method set up to handle that action.
The following code example shows how to define a BroadcastReceiver class to handle a received message reply intent:
  public class MyMessageReplyReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
        // If you set up the intent as described in
        // "Create conversation read and reply intents",
        // you can get the conversation ID by calling:
        int thisConversationId = intent.getIntExtra("conversation_id", -1).

    }

    /**
     * Get the message text from the intent.
     * Note that you should call
     * RemoteInput.getResultsFromIntent() to process
     * the RemoteInput.
     */
    private CharSequence getMessageText(Intent intent) {
        Bundle remoteInput =
            RemoteInput.getResultsFromIntent(intent);
        if (remoteInput != null) {
            return remoteInput.getCharSequence(MY_VOICE_REPLY_KEY);
        }
        return null;
    }
}

No comments:

Post a Comment