Android 5.0(L) 的MediaSession架构分析(转载)

Using Android Media Style notifications with Media Session controls

 ADD COMMENT Paul Trebilcox-Ruiz  Oct 30, 2014
Java Android User Interface Android Notifications

Android Lollipop is brimming with new features, and one of them is lock screen notifications. Up until this point, lock screen media controls had to be implemented through the use of a RemoteView, and media control notifications had to be built with custom views. In this tutorial I will go over using the new MediaStyle for notifications and interacting with a MediaSession for controlling media playback states. All code for this tutorial can be found on GitHub.

The very first thing that we're going to need to do is set the MEDIA_CONTENT_CONTROL permission in AndroidManifest.xml. This will allow us to use our lock screen notification to control media.

    
    
    
    
  1. android:name="android.permission.MEDIA_CONTENT_CONTROL" />

For this example we're going to use a background service to controls our media and build/interact with the new notifications. Our MainActivity is going to be very straight forward and simply start our service with an action telling the service to build a playing state notification.

    
    
    
    
  1. Intent intent = new Intent( getApplicationContext(), MediaPlayerService.class );
  2. intent.setAction( MediaPlayerService.ACTION_PLAY );
  3. startService( intent );

Next, we're going to want to start fleshing out MediaPlayerService. At the top of the class we're going to define a set of strings that we will use to implement notification actions, and also define the objects that we'll use throughout the class.

    
    
    
    
  1. public static final String ACTION_PLAY = "action_play";
  2. public static final String ACTION_PAUSE = "action_pause";
  3. public static final String ACTION_REWIND = "action_rewind";
  4. public static final String ACTION_FAST_FORWARD = "action_fast_foward";
  5. public static final String ACTION_NEXT = "action_next";
  6. public static final String ACTION_PREVIOUS = "action_previous";
  7. public static final String ACTION_STOP = "action_stop";
  8. private MediaPlayer mMediaPlayer;
  9. private MediaSessionManager mManager;
  10. private MediaSession mSession;
  11. private MediaController mController;

When the service receives an intent, it'll immediately go through onStartCommand. This method only does two simple things: if our objects have not been initialized, it'll call initMediaSession to set them up, and then the intent will be passed to handleIntent.

initMediaSession initializes the objects that we defined earlier. MediaPlayer handles media playback (not used in this example, but in an actual app it would be), the MediaSessionManagerhelps maintain the MediaSession, the MediaSession itself is used for keeping track of media states, and the MediaController handles transitioning between media states and callingMediaPlayer methods.

    
    
    
    
  1. mMediaPlayer = new MediaPlayer();
  2. mManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
  3. mSession = mManager.createSession("sample session");
  4. mController = MediaController.fromToken( mSession.getSessionToken() );

The next thing initMediaSession does is add TransportControlCallbacks that we can call in order to control the MediaPlayer and display new notifications.

    
    
    
    
  1. mSession.addTransportControlsCallback( new MediaSession.TransportControlsCallback() {
  2.     @Override
  3.     public void onPlay() {
  4.         super.onPlay();
  5.         Log.e( "MediaPlayerService", "onPlay");
  6.         buildNotification( generateAction( android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE ) );
  7.     }
  8.     @Override
  9.     public void onPause() {
  10.         super.onPause();
  11.         Log.e( "MediaPlayerService", "onPause");
  12.         buildNotification(generateAction(android.R.drawable.ic_media_play, "Play", ACTION_PLAY));
  13.     }
  14.     @Override
  15.     public void onSkipToNext() {
  16.         super.onSkipToNext();
  17.         Log.e( "MediaPlayerService", "onSkipToNext");
  18.         //Change media here
  19.         buildNotification( generateAction( android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE ) );
  20.     }
  21.     @Override
  22.     public void onSkipToPrevious() {
  23.         super.onSkipToPrevious();
  24.         Log.e( "MediaPlayerService", "onSkipToPrevious");
  25.         //Change media here
  26.         buildNotification( generateAction( android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE ) );
  27.     }
  28.     @Override
  29.     public void onFastForward() {
  30.         super.onFastForward();
  31.         Log.e( "MediaPlayerService", "onFastForward");
  32.         //Manipulate current media here
  33.     }
  34.     @Override
  35.     public void onRewind() {
  36.         super.onRewind();
  37.         Log.e( "MediaPlayerService", "onRewind");
  38.         //Manipulate current media here
  39.     }
  40.     @Override
  41.     public void onStop() {
  42.         super.onStop();
  43.         Log.e( "MediaPlayerService", "onStop");
  44.         //Stop media player here
  45.         NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
  46.         notificationManager.cancel( 1 );
  47.         Intent intent = new Intent( getApplicationContext(), MediaPlayerService.class );
  48.         stopService( intent );
  49.     }
  50.     @Override
  51.     public void onSeekTo(long pos) {
  52.         super.onSeekTo(pos);
  53.     }
  54.     @Override
  55.     public void onSetRating(Rating rating) {
  56.         super.onSetRating(rating);
  57.     }
  58. });

These control methods are called in handleIntent. When an intent is received by the service,handleIntent extracts the action associated with that intent to determine which transport control method should be called.

    
    
    
    
  1. private void handleIntent( Intent intent ) {
  2.     if( intent == null || intent.getAction() == null )
  3.         return;
  4.     String action = intent.getAction();
  5.     if( action.equalsIgnoreCase( ACTION_PLAY ) ) {
  6.         mController.getTransportControls().play();
  7.     } else if( action.equalsIgnoreCase( ACTION_PAUSE ) ) {
  8.         mController.getTransportControls().pause();
  9.     } else if( action.equalsIgnoreCase( ACTION_FAST_FORWARD ) ) {
  10.         mController.getTransportControls().fastForward();
  11.     } else if( action.equalsIgnoreCase( ACTION_REWIND ) ) {
  12.         mController.getTransportControls().rewind();
  13.     } else if( action.equalsIgnoreCase( ACTION_PREVIOUS ) ) {
  14.         mController.getTransportControls().skipToPrevious();
  15.     } else if( action.equalsIgnoreCase( ACTION_NEXT ) ) {
  16.         mController.getTransportControls().skipToNext();
  17.     } else if( action.equalsIgnoreCase( ACTION_STOP ) ) {
  18.         mController.getTransportControls().stop();
  19.     }
  20. }

As can be seen in the TransportControlCallbacks, we call buildNotification with another method called generateAction. Actions are used by the MediaStyle notification to populate the buttons at the bottom of the notification and launch intents when pressed. generateAction simply accepts the icon that the notification will use for that button, a title for the button and a string that will be used as the action identifier in handleIntent. With this information, generateAction is able to construct a pendingIntent before assigning it to an action that is then returned.

    
    
    
    
  1. private Notification.Action generateAction( int icon, String title, String intentAction ) {
  2.     Intent intent = new Intent( getApplicationContext(), MediaPlayerService.class );
  3.     intent.setAction( intentAction );
  4.     PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
  5.     return new Notification.Action.Builder( icon, title, pendingIntent ).build();
  6. }

buildNotification is where we actually implement the MediaStyle notification. The first thing we do is create a new Notification.MediaStyle style, then start building the rest of the notification through using Notification.Builder. This notification simply contains apendingIntent that would stop our media when the notification is dismissed, a title, content text, a small icon and the style.

    
    
    
    
  1. private void buildNotification( Notification.Action action ) {
  2.     Notification.MediaStyle style = new Notification.MediaStyle();
  3.     Intent intent = new Intent( getApplicationContext(), MediaPlayerService.class );
  4.     intent.setAction( ACTION_STOP );
  5.     PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
  6.     Notification.Builder builder = new Notification.Builder( this )
  7.             .setSmallIcon( R.drawable.ic_launcher )
  8.             .setContentTitle( "Media Title" )
  9.             .setContentText( "Media Artist" )
  10.             .setDeleteIntent( pendingIntent )
  11.             .setStyle( style );

Next we can add our buttons to the notification through the use of Builder.addAction. It should be noted that MediaStyle notifications only support up to five different actions. Each of our actions will be generated through the generateAction method described above.

    
    
    
    
  1. builder.addAction( generateAction( android.R.drawable.ic_media_previous, "Previous", ACTION_PREVIOUS ) );
  2. builder.addAction( generateAction( android.R.drawable.ic_media_rew, "Rewind", ACTION_REWIND ) );
  3. builder.addAction( action );
  4. builder.addAction( generateAction( android.R.drawable.ic_media_ff, "Fast Foward", ACTION_FAST_FORWARD ) );
  5. builder.addAction( generateAction( android.R.drawable.ic_media_next, "Next", ACTION_NEXT ) );

The last thing this method does is actually construct the notification and post it to the system

    
    
    
    
  1. NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
  2. notificationManager.notify( 1, builder.build() );

Now that the notification and sessions are implementing and working, the final thing we need to take into account is releasing our MediaSession once the media player and service have been stopped.

    
    
    
    
  1. @Override
  2. public boolean onUnbind(Intent intent) {
  3.     mSession.release();
  4.     return super.onUnbind(intent);
  5. }

And with that we now have a fully working MediaStyle notification on our lock screen and in the notification drawer that takes advantage of MediaSession for playback control. Enjoy!

Using Android Media Style notifications with Media Session controls

 ADD COMMENT Paul Trebilcox-Ruiz  Oct 30, 2014
Java Android User Interface Android Notifications

Android Lollipop is brimming with new features, and one of them is lock screen notifications. Up until this point, lock screen media controls had to be implemented through the use of a RemoteView, and media control notifications had to be built with custom views. In this tutorial I will go over using the new MediaStyle for notifications and interacting with a MediaSession for controlling media playback states. All code for this tutorial can be found on GitHub.

The very first thing that we're going to need to do is set the MEDIA_CONTENT_CONTROL permission in AndroidManifest.xml. This will allow us to use our lock screen notification to control media.

    
    
    
    
  1. android:name="android.permission.MEDIA_CONTENT_CONTROL" />

For this example we're going to use a background service to controls our media and build/interact with the new notifications. Our MainActivity is going to be very straight forward and simply start our service with an action telling the service to build a playing state notification.

    
    
    
    
  1. Intent intent = new Intent( getApplicationContext(), MediaPlayerService.class );
  2. intent.setAction( MediaPlayerService.ACTION_PLAY );
  3. startService( intent );

Next, we're going to want to start fleshing out MediaPlayerService. At the top of the class we're going to define a set of strings that we will use to implement notification actions, and also define the objects that we'll use throughout the class.

    
    
    
    
  1. public static final String ACTION_PLAY = "action_play";
  2. public static final String ACTION_PAUSE = "action_pause";
  3. public static final String ACTION_REWIND = "action_rewind";
  4. public static final String ACTION_FAST_FORWARD = "action_fast_foward";
  5. public static final String ACTION_NEXT = "action_next";
  6. public static final String ACTION_PREVIOUS = "action_previous";
  7. public static final String ACTION_STOP = "action_stop";
  8. private MediaPlayer mMediaPlayer;
  9. private MediaSessionManager mManager;
  10. private MediaSession mSession;
  11. private MediaController mController;

When the service receives an intent, it'll immediately go through onStartCommand. This method only does two simple things: if our objects have not been initialized, it'll call initMediaSession to set them up, and then the intent will be passed to handleIntent.

initMediaSession initializes the objects that we defined earlier. MediaPlayer handles media playback (not used in this example, but in an actual app it would be), the MediaSessionManagerhelps maintain the MediaSession, the MediaSession itself is used for keeping track of media states, and the MediaController handles transitioning between media states and callingMediaPlayer methods.

    
    
    
    
  1. mMediaPlayer = new MediaPlayer();
  2. mManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
  3. mSession = mManager.createSession("sample session");
  4. mController = MediaController.fromToken( mSession.getSessionToken() );

The next thing initMediaSession does is add TransportControlCallbacks that we can call in order to control the MediaPlayer and display new notifications.

    
    
    
    
  1. mSession.addTransportControlsCallback( new MediaSession.TransportControlsCallback() {
  2.     @Override
  3.     public void onPlay() {
  4.         super.onPlay();
  5.         Log.e( "MediaPlayerService", "onPlay");
  6.         buildNotification( generateAction( android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE ) );
  7.     }
  8.     @Override
  9.     public void onPause() {
  10.         super.onPause();
  11.         Log.e( "MediaPlayerService", "onPause");
  12.         buildNotification(generateAction(android.R.drawable.ic_media_play, "Play", ACTION_PLAY));
  13.     }
  14.     @Override
  15.     public void onSkipToNext() {
  16.         super.onSkipToNext();
  17.         Log.e( "MediaPlayerService", "onSkipToNext");
  18.         //Change media here
  19.         buildNotification( generateAction( android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE ) );
  20.     }
  21.     @Override
  22.     public void onSkipToPrevious() {
  23.         super.onSkipToPrevious();
  24.         Log.e( "MediaPlayerService", "onSkipToPrevious");
  25.         //Change media here
  26.         buildNotification( generateAction( android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE ) );
  27.     }
  28.     @Override
  29.     public void onFastForward() {
  30.         super.onFastForward();
  31.         Log.e( "MediaPlayerService", "onFastForward");
  32.         //Manipulate current media here
  33.     }
  34.     @Override
  35.     public void onRewind() {
  36.         super.onRewind();
  37.         Log.e( "MediaPlayerService", "onRewind");
  38.         //Manipulate current media here
  39.     }
  40.     @Override
  41.     public void onStop() {
  42.         super.onStop();
  43.         Log.e( "MediaPlayerService", "onStop");
  44.         //Stop media player here
  45.         NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
  46.         notificationManager.cancel( 1 );
  47.         Intent intent = new Intent( getApplicationContext(), MediaPlayerService.class );
  48.         stopService( intent );
  49.     }
  50.     @Override
  51.     public void onSeekTo(long pos) {
  52.         super.onSeekTo(pos);
  53.     }
  54.     @Override
  55.     public void onSetRating(Rating rating) {
  56.         super.onSetRating(rating);
  57.     }
  58. });

These control methods are called in handleIntent. When an intent is received by the service,handleIntent extracts the action associated with that intent to determine which transport control method should be called.

    
    
    
    
  1. private void handleIntent( Intent intent ) {
  2.     if( intent == null || intent.getAction() == null )
  3.         return;
  4.     String action = intent.getAction();
  5.     if( action.equalsIgnoreCase( ACTION_PLAY ) ) {
  6.         mController.getTransportControls().play();
  7.     } else if( action.equalsIgnoreCase( ACTION_PAUSE ) ) {
  8.         mController.getTransportControls().pause();
  9.     } else if( action.equalsIgnoreCase( ACTION_FAST_FORWARD ) ) {
  10.         mController.getTransportControls().fastForward();
  11.     } else if( action.equalsIgnoreCase( ACTION_REWIND ) ) {
  12.         mController.getTransportControls().rewind();
  13.     } else if( action.equalsIgnoreCase( ACTION_PREVIOUS ) ) {
  14.         mController.getTransportControls().skipToPrevious();
  15.     } else if( action.equalsIgnoreCase( ACTION_NEXT ) ) {
  16.         mController.getTransportControls().skipToNext();
  17.     } else if( action.equalsIgnoreCase( ACTION_STOP ) ) {
  18.         mController.getTransportControls().stop();
  19.     }
  20. }

As can be seen in the TransportControlCallbacks, we call buildNotification with another method called generateAction. Actions are used by the MediaStyle notification to populate the buttons at the bottom of the notification and launch intents when pressed. generateAction simply accepts the icon that the notification will use for that button, a title for the button and a string that will be used as the action identifier in handleIntent. With this information, generateAction is able to construct a pendingIntent before assigning it to an action that is then returned.

    
    
    
    
  1. private Notification.Action generateAction( int icon, String title, String intentAction ) {
  2.     Intent intent = new Intent( getApplicationContext(), MediaPlayerService.class );
  3.     intent.setAction( intentAction );
  4.     PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
  5.     return new Notification.Action.Builder( icon, title, pendingIntent ).build();
  6. }

buildNotification is where we actually implement the MediaStyle notification. The first thing we do is create a new Notification.MediaStyle style, then start building the rest of the notification through using Notification.Builder. This notification simply contains apendingIntent that would stop our media when the notification is dismissed, a title, content text, a small icon and the style.

    
    
    
    
  1. private void buildNotification( Notification.Action action ) {
  2.     Notification.MediaStyle style = new Notification.MediaStyle();
  3.     Intent intent = new Intent( getApplicationContext(), MediaPlayerService.class );
  4.     intent.setAction( ACTION_STOP );
  5.     PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
  6.     Notification.Builder builder = new Notification.Builder( this )
  7.             .setSmallIcon( R.drawable.ic_launcher )
  8.             .setContentTitle( "Media Title" )
  9.             .setContentText( "Media Artist" )
  10.             .setDeleteIntent( pendingIntent )
  11.             .setStyle( style );

Next we can add our buttons to the notification through the use of Builder.addAction. It should be noted that MediaStyle notifications only support up to five different actions. Each of our actions will be generated through the generateAction method described above.

    
    
    
    
  1. builder.addAction( generateAction( android.R.drawable.ic_media_previous, "Previous", ACTION_PREVIOUS ) );
  2. builder.addAction( generateAction( android.R.drawable.ic_media_rew, "Rewind", ACTION_REWIND ) );
  3. builder.addAction( action );
  4. builder.addAction( generateAction( android.R.drawable.ic_media_ff, "Fast Foward", ACTION_FAST_FORWARD ) );
  5. builder.addAction( generateAction( android.R.drawable.ic_media_next, "Next", ACTION_NEXT ) );

The last thing this method does is actually construct the notification and post it to the system

    
    
    
    
  1. NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
  2. notificationManager.notify( 1, builder.build() );

Now that the notification and sessions are implementing and working, the final thing we need to take into account is releasing our MediaSession once the media player and service have been stopped.

    
    
    
    
  1. @Override
  2. public boolean onUnbind(Intent intent) {
  3.     mSession.release();
  4.     return super.onUnbind(intent);
  5. }

And with that we now have a fully working MediaStyle notification on our lock screen and in the notification drawer that takes advantage of MediaSession for playback control. Enjoy!

你可能感兴趣的:(android)