Java Code Examples for android.support.v4.media.session.MediaSessionCompat#Token

The following examples show how to use android.support.v4.media.session.MediaSessionCompat#Token . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MediaNotificationManager.java    From carstream-android-auto with Apache License 2.0 6 votes vote down vote up
public MediaNotificationManager(Context context, MediaSessionCompat.Token sessionToken) throws RemoteException {
    mContext = context;
    mSessionToken = sessionToken;
    updateSessionToken();

    mNotificationManager = NotificationManagerCompat.from(context);

    String pkg = context.getPackageName();
    mPauseIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_PAUSE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mPlayIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_PLAY).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mPreviousIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mNextIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_NEXT).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mStopIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_STOP).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mStopCastIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
            new Intent(ACTION_STOP_CASTING).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);

    // Cancel all notifications to handle the case where the Service was killed and
    // restarted by the system.
    mNotificationManager.cancelAll();
}
 
Example 2
Source File: ServicePlayerController.java    From Jockey with Apache License 2.0 6 votes vote down vote up
private void fetchMediaSessionToken() {
    if (mBinding == null) {
        return;
    }

    if (!mMediaSessionToken.hasValue() || mMediaSessionToken.getValue() == null) {
        MediaSessionCompat.Token token = null;

        try {
            token = mBinding.getMediaSessionToken();
        } catch (RemoteException e) {
            Timber.e(e, "Failed to get session token");
        }

        if (token != null) {
            mMediaSessionToken.onNext(token);
        }
    }
}
 
Example 3
Source File: MusicPlayerActivity.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
@Override
public void onMediaItemSelected(MediaBrowserCompat.MediaItem item) {
    LogUtils.d(TAG, "onMediaItemSelected, mediaId=" + item.getMediaId());
    if (item.isPlayable()) {
        final MediaControllerCompat mediaController = getSupportMediaController();
        if (mediaController != null) {
            MediaSessionCompat.Token token = mediaController.getSessionToken();
            MediaControllerCompat.TransportControls tc = mediaController.getTransportControls();
            mediaController.getTransportControls().playFromMediaId(item.getMediaId(), null);
        }
    } else if (item.isBrowsable()) {
        navigateToBrowser(item.getMediaId());
    } else {
        LogUtils.w(TAG, "Ignoring MediaItem that is neither browsable nor playable: ",
                "mediaId=", item.getMediaId());
    }
}
 
Example 4
Source File: PlaybackControlBaseActivity.java    From LyricHere with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnected() {
    LogUtils.d(TAG, "onConnected");

    MediaSessionCompat.Token token = mMediaBrowser.getSessionToken();
    if (token == null) {
        throw new IllegalArgumentException("No Session token");
    }
    connectToSession(token);
}
 
Example 5
Source File: PlayerNotification.java    From blade-player with GNU General Public License v3.0 5 votes vote down vote up
private NotificationCompat.Builder buildNotification(int playerState, MediaSessionCompat.Token token, Song playing)
{
    if(Build.VERSION.SDK_INT >= 26) createChannel();

    boolean isPlaying = (playerState == PlayerMediaPlayer.PLAYER_STATE_PLAYING);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(mService, CHANNEL_ID);

    Intent openUI = new Intent(mService, PlayActivity.class);
    openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(mService, REQUEST_CODE, openUI, PendingIntent.FLAG_CANCEL_CURRENT);

    MediaStyle style = new MediaStyle()
            .setMediaSession(token)
            .setShowActionsInCompactView(0, 1, 2)
            .setShowCancelButton(true)
            .setCancelButtonIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(mService, PlaybackStateCompat.ACTION_STOP));

    builder.setStyle(style)
            .setWhen(0) //remove 'now' text on notification top
            //.setSubText("") //text between 'Blade' and 'Now' (notification top)
            .setColor(ContextCompat.getColor(mService, ThemesActivity.currentColorPrimary))
            .setSmallIcon(R.drawable.app_icon_notif) //icon that will be displayed in status bar
            .setContentIntent(contentIntent) //intent that will be sent on notification click
            .setLargeIcon(mService.getCurrentArt() == null ? BitmapFactory.decodeResource(mService.getResources(), R.drawable.ic_albums) : mService.getCurrentArt())
            .setContentTitle(playing.getTitle())
            .setContentText(playing.getArtist().getName() + " - " + playing.getAlbum().getName())
            .setDeleteIntent(null) //intent on notification slide
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setOngoing(isPlaying); //disable swipe delete if playing

    builder.addAction(mPrevAction);
    builder.addAction(isPlaying ? mPauseAction : mPlayAction);
    builder.addAction(mNextAction);

    return builder;
}
 
Example 6
Source File: TrackFragment.java    From Melophile with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnected() {
  super.onConnected();
  MediaSessionCompat.Token token = browserCompat.getSessionToken();
  try {
    MediaControllerCompat mediaController = new MediaControllerCompat(getActivity(), token);
    // Save the controller
    mediaController.registerCallback(controllerCallback);
    MediaControllerCompat.setMediaController(getActivity(), mediaController);
    //inject the passed query
    inject();
  } catch (RemoteException ex) {
    ex.printStackTrace();
  }
}
 
Example 7
Source File: MediaNotificationManager.java    From android-MediaBrowserService with Apache License 2.0 5 votes vote down vote up
public Notification getNotification(MediaMetadataCompat metadata,
                                    @NonNull PlaybackStateCompat state,
                                    MediaSessionCompat.Token token) {
    boolean isPlaying = state.getState() == PlaybackStateCompat.STATE_PLAYING;
    MediaDescriptionCompat description = metadata.getDescription();
    NotificationCompat.Builder builder =
            buildNotification(state, token, isPlaying, description);
    return builder.build();
}
 
Example 8
Source File: MockPlayerController.java    From Jockey with Apache License 2.0 4 votes vote down vote up
@Override
public Observable<MediaSessionCompat.Token> getMediaSessionToken() {
    throw new UnsupportedOperationException("Stub!");
}
 
Example 9
Source File: MediaNotificationManager.java    From android-MediaBrowserService with Apache License 2.0 4 votes vote down vote up
private NotificationCompat.Builder buildNotification(@NonNull PlaybackStateCompat state,
                                                     MediaSessionCompat.Token token,
                                                     boolean isPlaying,
                                                     MediaDescriptionCompat description) {

    // Create the (mandatory) notification channel when running on Android Oreo.
    if (isAndroidOOrHigher()) {
        createChannel();
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(mService, CHANNEL_ID);
    builder.setStyle(
            new MediaStyle()
                    .setMediaSession(token)
                    .setShowActionsInCompactView(0, 1, 2)
                    // For backwards compatibility with Android L and earlier.
                    .setShowCancelButton(true)
                    .setCancelButtonIntent(
                            MediaButtonReceiver.buildMediaButtonPendingIntent(
                                    mService,
                                    PlaybackStateCompat.ACTION_STOP)))
            .setColor(ContextCompat.getColor(mService, R.color.notification_bg))
            .setSmallIcon(R.drawable.ic_stat_image_audiotrack)
            // Pending intent that is fired when user clicks on notification.
            .setContentIntent(createContentIntent())
            // Title - Usually Song name.
            .setContentTitle(description.getTitle())
            // Subtitle - Usually Artist name.
            .setContentText(description.getSubtitle())
            .setLargeIcon(MusicLibrary.getAlbumBitmap(mService, description.getMediaId()))
            // When notification is deleted (when playback is paused and notification can be
            // deleted) fire MediaButtonPendingIntent with ACTION_STOP.
            .setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(
                    mService, PlaybackStateCompat.ACTION_STOP))
            // Show controls on lock screen even when user hides sensitive content.
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

    // If skip to next action is enabled.
    if ((state.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0) {
        builder.addAction(mPrevAction);
    }

    builder.addAction(isPlaying ? mPauseAction : mPlayAction);

    // If skip to prev action is enabled.
    if ((state.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
        builder.addAction(mNextAction);
    }

    return builder;
}
 
Example 10
Source File: OdysseyNotificationManager.java    From odyssey with GNU General Public License v3.0 4 votes vote down vote up
public synchronized void updateNotification(TrackModel track, PlaybackService.PLAYSTATE state, MediaSessionCompat.Token mediaSessionToken) {
    mLastState = state;
    mLastToken = mediaSessionToken;
    if (track != null) {
        openChannel();
        mNotificationBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID);

        // Open application intent
        Intent mainIntent = new Intent(mContext, OdysseySplashActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
        mainIntent.putExtra(OdysseyMainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW, OdysseyMainActivity.REQUESTEDVIEW.NOWPLAYING.ordinal());
        PendingIntent contentPendingIntent = PendingIntent.getActivity(mContext, NOTIFICATION_INTENT_OPENGUI, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationBuilder.setContentIntent(contentPendingIntent);

        // Set pendingintents
        // Previous song action
        Intent prevIntent = new Intent(PlaybackService.ACTION_PREVIOUS);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PREVIOUS, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action prevAction = new NotificationCompat.Action.Builder(R.drawable.ic_skip_previous_48dp, "Previous", prevPendingIntent).build();

        // Pause/Play action
        PendingIntent playPauseIntent;
        int playPauseIcon;
        if (state == PlaybackService.PLAYSTATE.PLAYING) {
            Intent pauseIntent = new Intent(PlaybackService.ACTION_PAUSE);
            playPauseIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PLAYPAUSE, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            playPauseIcon = R.drawable.ic_pause_48dp;
        } else {
            Intent playIntent = new Intent(PlaybackService.ACTION_PLAY);
            playPauseIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PLAYPAUSE, playIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            playPauseIcon = R.drawable.ic_play_arrow_48dp;
        }
        NotificationCompat.Action playPauseAction = new NotificationCompat.Action.Builder(playPauseIcon, "PlayPause", playPauseIntent).build();

        // Next song action
        Intent nextIntent = new Intent(PlaybackService.ACTION_NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_NEXT, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action nextAction = new NotificationCompat.Action.Builder(R.drawable.ic_skip_next_48dp, "Next", nextPendingIntent).build();

        // Quit action
        Intent quitIntent = new Intent(PlaybackService.ACTION_QUIT);
        PendingIntent quitPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_QUIT, quitIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationBuilder.setDeleteIntent(quitPendingIntent);

        mNotificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        mNotificationBuilder.setSmallIcon(R.drawable.odyssey_notification);
        mNotificationBuilder.addAction(prevAction);
        mNotificationBuilder.addAction(playPauseAction);
        mNotificationBuilder.addAction(nextAction);
        androidx.media.app.NotificationCompat.MediaStyle notificationStyle = new androidx.media.app.NotificationCompat.MediaStyle();
        notificationStyle.setShowActionsInCompactView(1, 2);
        notificationStyle.setMediaSession(mediaSessionToken);
        mNotificationBuilder.setStyle(notificationStyle);
        mNotificationBuilder.setContentTitle(mContext.getResources().getString(R.string.notification_sensitive_content_replacement));

        // Remove unnecessary time info
        mNotificationBuilder.setShowWhen(false);

        //Build the public notification
        Notification notificationPublic = mNotificationBuilder.build();

        mNotificationBuilder.setContentTitle(track.getTrackDisplayedName());
        mNotificationBuilder.setContentText(track.getTrackArtistName());

        // Cover but only if changed
        if (mLastTrack == null || !track.getTrackAlbumKey().equals(mLastTrack.getTrackAlbumKey())) {
            mLastTrack = track;
            mLastBitmap = null;
        }

        // Only set image if an saved one is available
        if (mLastBitmap != null && !mHideArtwork) {
            mNotificationBuilder.setLargeIcon(mLastBitmap);
        }

        // Build the private notification
        if (mHideMediaOnLockscreen) {
            mNotificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
        }

        mNotification = mNotificationBuilder.build();
        mNotification.publicVersion = notificationPublic;

        // Check if run from service and check if playing or pause.
        // Pause notification should be dismissible.
        if (mContext instanceof Service) {
            if (state == PlaybackService.PLAYSTATE.PLAYING) {
                ((Service) mContext).startForeground(NOTIFICATION_ID, mNotification);
            } else {
                ((Service) mContext).stopForeground(false);
            }
        }

        // Send the notification away
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }

}
 
Example 11
Source File: MediaNotificationManager.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
public Notification buildNotification(MediaSessionCompat.Token sessionToken)
{
    LogHelper.d(TAG, "updateNotificationMetadata. currentYouTubeVideo=" + currentYouTubeVideo);
    if (currentYouTubeVideo == null || playbackState == null) return null;

    if (shouldCreateNowRunningChannel()) {
        createNotificationChannel();
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);

    // Only add actions for skip back, play/pause, skip forward, based on what's enabled.
    int playPauseIndex = 0;
    if (isSkipToPreviousEnabled()) {
        builder.addAction(skipToPreviousAction);
        playPauseIndex++;
    }

    if (isPlaying()) {
        builder.addAction(pauseAction);
    } else if (isPlayEnabled()) {
        builder.addAction(playAction);
    }

    if (isSkipToNextEnabled()) {
        builder.addAction(skipToNextAction);
    }

    MediaStyle mediaStyle = new MediaStyle()
            .setMediaSession(sessionToken)
            .setShowActionsInCompactView(playPauseIndex)
            .setShowCancelButton(true)
            .setCancelButtonIntent(stopPendingIntent);

    builder.setContentIntent(mediaController.getSessionActivity())
            .setContentTitle(currentYouTubeVideo.getTitle())
            .setContentInfo(currentYouTubeVideo.getDuration())
            .setSubText(Utils.formatViewCount(currentYouTubeVideo.getViewCount()))
            .setContentIntent(clickPendingIntent)
            .setDeleteIntent(stopPendingIntent)
            .setOnlyAlertOnce(true)
            .setUsesChronometer(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setStyle(mediaStyle)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);


    if (isPlaying() && playbackState.getPosition() > 0) {
        builder
                .setWhen(System.currentTimeMillis() - playbackState.getPosition())
                .setShowWhen(true)
                .setUsesChronometer(true);
    } else {
        builder
                .setWhen(0)
                .setShowWhen(false)
                .setUsesChronometer(false);
    }

    // Load bitmap
    if (currentYouTubeVideo.getThumbnailURL() != null && !currentYouTubeVideo.getThumbnailURL().isEmpty()) {
        target.setNotificationBuilder(builder);
        Picasso.with(exoAudioService)
                .load(currentYouTubeVideo.getThumbnailURL())
                .resize(Config.MAX_WIDTH_ICON, Config.MAX_HEIGHT_ICON)
                .centerCrop()
                .into(target);
    }

    return builder.build();
}
 
Example 12
Source File: NotificationBuilder.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
public Notification buildNotification(MediaSessionCompat.Token sessionToken) throws RemoteException
{
    if (shouldCreateNowRunningChannel()) {
        createNotificationChannel();
    }
    mediaController = new MediaControllerCompat(context, sessionToken);
    MediaMetadataCompat metadata = mediaController.getMetadata();
    mediaDescription = metadata.getDescription();
    playbackState = mediaController.getPlaybackState();

    builder = new NotificationCompat.Builder(context, CHANNEL_ID);

    // Only add actions for skip back, play/pause, skip forward, based on what's enabled.
    int playPauseIndex = 0;
    if (isSkipToPreviousEnabled()) {
        builder.addAction(skipToPreviousAction);
        playPauseIndex++;
    }

    if (isPlaying()) {
        builder.addAction(pauseAction);
    } else if (isPlayEnabled()) {
        builder.addAction(playAction);
    }

    if (isSkipToNextEnabled()) {
        builder.addAction(skipToNextAction);
    }

    MediaStyle mediaStyle = new MediaStyle()
            .setCancelButtonIntent(stopPendingIntent)
            .setMediaSession(sessionToken)
            .setShowActionsInCompactView(playPauseIndex)
            .setShowCancelButton(true);

    return builder.setContentIntent(mediaController.getSessionActivity())
            .setContentText(mediaDescription.getSubtitle())
            .setContentTitle(mediaDescription.getTitle())
            .setDeleteIntent(stopPendingIntent)
            .setLargeIcon(mediaDescription.getIconBitmap())
            .setOnlyAlertOnce(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setStyle(mediaStyle)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .build();
}
 
Example 13
Source File: ServicePlayerController.java    From Jockey with Apache License 2.0 4 votes vote down vote up
@Override
public Observable<MediaSessionCompat.Token> getMediaSessionToken() {
    return mMediaSessionToken.filter(token -> token != null);
}
 
Example 14
Source File: AudioPlayerService.java    From react-native-streaming-audio-player with MIT License 4 votes vote down vote up
public MediaSessionCompat.Token getMediaSessionToken() {
    return mMediaSession.getSessionToken();
}
 
Example 15
Source File: PlayerService.java    From AndroidAudioExample with MIT License 4 votes vote down vote up
public MediaSessionCompat.Token getMediaSessionToken() {
    return mediaSession.getSessionToken();
}
 
Example 16
Source File: MainActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main_activity);

  // Create the MediaBrowserCompat
  mMediaBrowser = new MediaBrowserCompat(
    this,
    new ComponentName(this, MediaPlaybackService.class),
    new MediaBrowserCompat.ConnectionCallback() {
      @Override
      public void onConnected() {
        try {
          // We can construct a media controller from the session's token
          MediaSessionCompat.Token token = mMediaBrowser.getSessionToken();
          mMediaController = new MediaControllerCompat(MainActivity.this, token);

          // Listing 17-9: Keeping your UI in sync with playback state and metadata changes
          mMediaController.registerCallback(new MediaControllerCompat.Callback() {
            @Override
            public void onPlaybackStateChanged(PlaybackStateCompat state) {
              // Update the UI based on playback state change.
            }

            @Override
            public void onMetadataChanged(MediaMetadataCompat metadata) {
              // Update the UI based on Media Metadata change.
            }
          });
        } catch (RemoteException e) {
          Log.e(TAG, "Error creating controller", e);
        }
      }

      @Override
      public void onConnectionSuspended() {
        // We were connected, but no longer are.
      }

      @Override
      public void onConnectionFailed() {
        // The attempt to connect failed completely.
        // Check the ComponentName!
      }
    },
    null);
  mMediaBrowser.connect();
}
 
Example 17
Source File: TtsService.java    From android-app with GNU General Public License v3.0 4 votes vote down vote up
public MediaSessionCompat.Token getMediaSessionToken() {
    return mediaSession.getSessionToken();
}
 
Example 18
Source File: AudioPlayerService.java    From react-native-audio-streaming-player with MIT License 4 votes vote down vote up
public MediaSessionCompat.Token getMediaSessionToken() {
    return mMediaSession.getSessionToken();
}
 
Example 19
Source File: PlayerService.java    From blade-player with GNU General Public License v3.0 votes vote down vote up
public MediaSessionCompat.Token getSessionToken() {return mSession.getSessionToken();} 
Example 20
Source File: PlayerController.java    From Jockey with Apache License 2.0 votes vote down vote up
Observable<MediaSessionCompat.Token> getMediaSessionToken();