android auto-Providing Audio Playback for Auto

desaco發表於2016-01-23

> Providing Audio Playback for Auto

 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 simple, yet customizable user interface.

> 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.

 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>
 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 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.

> The broadcasted intent has a String extra media_connection_status, that contains either media_connected ormedia_disconnected string that represents the current connection status.

IntentFilter filter = new IntentFilter("com.google.android.gms.car.media.STATUS");
BroadcastReceiver receiver = new BroadcastReceiver() {
    ...
    public void onReceive(Context context, Intent intent) {
        String status = intent.getStringExtra("media_connection_status");
        boolean isConnectedToCar = "media_connected".equals(status);
        // adjust settings based on the connection status
    }
};
registerReceiver(receiver, filter);
   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

 > 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().

@Override
public BrowserRoot onGetRoot(String clientPackageName, int clientUid,
    Bundle rootHints) {

    // Verify that the specified package is allowed to access your
    // content! You'll need to write your own logic to do this.
    if (!isValid(clientPackageName, clientUid)) {
        // If the request comes from an untrusted package, return null.
        // No further calls will be made to other media browsing methods.

        return null;
    }

    return new BrowserRoot(MY_MEDIA_ROOT_ID, null);
}
@Override
public void onLoadChildren(final String parentMediaId,
    final Result<List<MediaItem>> result) {

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

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

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

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

        // examine the passed parentMediaId to see which submenu we're at,
        // and put the children of that menu in the mediaItems list
    }
    result.sendResult(mediaItems);
}
 To reduce driver distractions, you can add voice actions in your audio playback app. With voice action support, users can launch your app and play audio by providing voice input on Auto screens. If your audio playback app is already active and the user says “Play a song”, the system starts playing music without requiring the user to look at or touch the screen.

 To parse the voice search query to play back audio content in your app, follow these steps:

  1. Use the extras bundle and search query string returned from the voice search to filter results.
  2. Build the audio content queue based on these results.
  3. Play the audio content.

The following extras are supported in Android Auto:

 >The following snippet shows how to override the onPlayFromSearch() method in yourMediaSession.Callback implementation to handle the search query and extras for playing audio content in your app:

@Override
public void onPlayFromSearch(String query, Bundle extras) {
    if (TextUtils.isEmpty(query)) {
        // The user provided generic string e.g. 'Play music'
        // Build appropriate playlist queue
    } else {
        // Build a queue based on songs that match "query" or "extras" param
        String mediaFocus = extras.getString(MediaStore.EXTRA_MEDIA_FOCUS);
        if (TextUtils.equals(mediaFocus,
                MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE)) {
            isArtistFocus = true;
            artist = extras.getString(MediaStore.EXTRA_MEDIA_ARTIST);
        } else if (TextUtils.equals(mediaFocus,
                MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE)) {
            isAlbumFocus = true;
            album = extras.getString(MediaStore.EXTRA_MEDIA_ALBUM);
        }

        // Implement additional "extras" param filtering
    }

    // Implement your logic to retrieve the queue
    if (isArtistFocus) {
        result = searchMusicByArtist(artist);
    } else if (isAlbumFocus) {
        result = searchMusicByAlbum(album);
    }

    if (result == null) {
        // No focus found, search by query for song title
        result = searchMusicBySongTitle(query);
    }

    if (result != null && !result.isEmpty()) {
        // Immediately start playing from the beginning of the search results
        // Implement your logic to start playing music
        playMusic(result);
    } else {
        // Handle no queue found. Stop playing if the app
        // is currently playing a song
    }
}

Note: To minimize driver distractions, immediately initiate audio content playback in theonPlayFromSearch() method when you have generated the audio content queue based on the user's request.

 > To provide voice-enabled playback controls, first enable the hardware controls by setting these flags in your app’s MediaSession object:

mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
    MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);

Then, implement the callback methods with the playback controls that you support in your app. Here’s a list of voice-enabled playback controls supported by Android Auto:

Example phrase Callback method
"Next song" onSkipToNext()
"Previous song" onSkipToPrevious()
"Pause music" onPause()
"Stop music" onStop()
"Resume music" onPlay()

相關文章