Java Code Examples for android.support.v4.media.session.PlaybackStateCompat#ACTION_SKIP_TO_PREVIOUS

The following examples show how to use android.support.v4.media.session.PlaybackStateCompat#ACTION_SKIP_TO_PREVIOUS . 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: MusicService.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
private long getAvailableActions() {
    long actions = PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID |
            PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH;
    if (mPlayingQueue == null || mPlayingQueue.isEmpty()) {
        return actions;
    }
    if (mPlayback.isPlaying()) {
        actions |= PlaybackStateCompat.ACTION_PAUSE;
    }
    if (mCurrentIndexOnQueue > 0) {
        actions |= PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS;
    }
    if (mCurrentIndexOnQueue < mPlayingQueue.size() - 1) {
        actions |= PlaybackStateCompat.ACTION_SKIP_TO_NEXT;
    }
    return actions;
}
 
Example 2
Source File: RemoteControlClientLP.java    From Popeens-DSub with GNU General Public License v3.0 6 votes vote down vote up
protected long getPlaybackActions(boolean isSong, int currentIndex, int size) {
	long actions = PlaybackStateCompat.ACTION_PLAY |
			PlaybackStateCompat.ACTION_PAUSE |
			PlaybackStateCompat.ACTION_SEEK_TO |
			PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM;

	if(isSong) {
		if (currentIndex > 0) {
			actions |= PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS;
		}
		if (currentIndex < size - 1) {
			actions |= PlaybackStateCompat.ACTION_SKIP_TO_NEXT;
		}
	} else {
		actions |= PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS;
		actions |= PlaybackStateCompat.ACTION_SKIP_TO_NEXT;
	}

	return actions;
}
 
Example 3
Source File: MusicControlNotification.java    From react-native-music-control with MIT License 6 votes vote down vote up
/**
 * Code taken from newer version of the support library located in PlaybackStateCompat.toKeyCode
 * Replace this to PlaybackStateCompat.toKeyCode when React Native updates the support library
 */
private int toKeyCode(long action) {
    if (action == PlaybackStateCompat.ACTION_PLAY) {
        return KeyEvent.KEYCODE_MEDIA_PLAY;
    } else if (action == PlaybackStateCompat.ACTION_PAUSE) {
        return KeyEvent.KEYCODE_MEDIA_PAUSE;
    } else if (action == PlaybackStateCompat.ACTION_SKIP_TO_NEXT) {
        return KeyEvent.KEYCODE_MEDIA_NEXT;
    } else if (action == PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) {
        return KeyEvent.KEYCODE_MEDIA_PREVIOUS;
    } else if (action == PlaybackStateCompat.ACTION_STOP) {
        return KeyEvent.KEYCODE_MEDIA_STOP;
    } else if (action == PlaybackStateCompat.ACTION_FAST_FORWARD) {
        return KeyEvent.KEYCODE_MEDIA_FAST_FORWARD;
    } else if (action == PlaybackStateCompat.ACTION_REWIND) {
        return KeyEvent.KEYCODE_MEDIA_REWIND;
    } else if (action == PlaybackStateCompat.ACTION_PLAY_PAUSE) {
        return KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
    }
    return KeyEvent.KEYCODE_UNKNOWN;
}
 
Example 4
Source File: PlaybackManager.java    From Melophile with Apache License 2.0 6 votes vote down vote up
private long getAvailableActions() {
  long actions =
          PlaybackStateCompat.ACTION_PLAY_PAUSE |
                  PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID |
                  PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH |
                  PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
                  PlaybackStateCompat.ACTION_SKIP_TO_NEXT;
  if (playback.isPlaying()) {
    actions |= PlaybackStateCompat.ACTION_PAUSE;
  } else {
    actions |= PlaybackStateCompat.ACTION_PLAY;
  }
  //
  if (isRepeat) {
    actions |= PlaybackStateCompat.ACTION_SET_REPEAT_MODE;
  }
  //
  if (isShuffle) {
    actions |= PlaybackStateCompat.ACTION_SET_SHUFFLE_MODE_ENABLED;
  }
  return actions;
}
 
Example 5
Source File: MediaSessionManager.java    From react-native-jw-media-player with MIT License 5 votes vote down vote up
public @PlaybackStateCompat.Actions
long getCapabilities(PlayerState playerState) {
	long capabilities = 0;

	switch (playerState) {
		case PLAYING:
			capabilities |= PlaybackStateCompat.ACTION_PAUSE
					| PlaybackStateCompat.ACTION_STOP
					| PlaybackStateCompat.ACTION_SEEK_TO;
			break;
		case PAUSED:
			capabilities |= PlaybackStateCompat.ACTION_PLAY
					| PlaybackStateCompat.ACTION_STOP
					| PlaybackStateCompat.ACTION_SEEK_TO;
			break;
		case BUFFERING:
			capabilities |= PlaybackStateCompat.ACTION_PAUSE
					| PlaybackStateCompat.ACTION_STOP
					| PlaybackStateCompat.ACTION_SEEK_TO;
			break;
		case IDLE:
			if (!mReceivedError && mPlaylist != null && mPlaylist.size() >= 1) {
				capabilities |= PlaybackStateCompat.ACTION_PLAY;
			}
			break;
	}

	if (mPlaylist != null && mPlaylist.size() - mPlaylistIndex > 1) {
		capabilities |= PlaybackStateCompat.ACTION_SKIP_TO_NEXT;
	}

	if (mPlaylistIndex > 0 && mPlaylist != null && mPlaylist.size() > 1) {
		capabilities |= PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS;
	}

	return capabilities;
}
 
Example 6
Source File: MediaNotificationManager.java    From carstream-android-auto with Apache License 2.0 5 votes vote down vote up
private int addActions(final NotificationCompat.Builder notificationBuilder) {
    Log.d(TAG, "updatePlayPauseAction");

    int playPauseButtonPosition = 0;
    // If skip to previous action is enabled
    if ((mPlaybackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0) {
        notificationBuilder.addAction(R.drawable.ic_prev,
                "Previous", mPreviousIntent);

        // If there is a "skip to previous" button, the playVideo/pauseVideo button will
        // be the second one. We need to keep track of it, because the MediaStyle notification
        // requires to specify the index of the buttons (actions) that should be visible
        // when in compact view.
        playPauseButtonPosition = 1;
    }

    // Play or pauseVideo button, depending on the current state.
    final String label;
    final int icon;
    final PendingIntent intent;
    if (mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
        label = "Pause";
        icon = R.drawable.ic_pause;
        intent = mPauseIntent;
    } else {
        label = "Play";
        icon = R.drawable.ic_play;
        intent = mPlayIntent;
    }
    notificationBuilder.addAction(new NotificationCompat.Action(icon, label, intent));

    // If skip to next action is enabled
    if ((mPlaybackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
        notificationBuilder.addAction(R.drawable.ic_next,
                "Next", mNextIntent);
    }

    return playPauseButtonPosition;
}
 
Example 7
Source File: MyMediaBrowserService.java    From carstream-android-auto with Apache License 2.0 5 votes vote down vote up
private long getAvailableActions() {
    long actions =
            PlaybackStateCompat.ACTION_PLAY_PAUSE |
                    PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID |
                    PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH |
                    PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
                    PlaybackStateCompat.ACTION_SKIP_TO_NEXT;
    return actions;
}
 
Example 8
Source File: MediaPlayerAdapter.java    From android-MediaBrowserService with Apache License 2.0 5 votes vote down vote up
/**
 * Set the current capabilities available on this session. Note: If a capability is not
 * listed in the bitmask of capabilities then the MediaSession will not handle it. For
 * example, if you don't want ACTION_STOP to be handled by the MediaSession, then don't
 * included it in the bitmask that's returned.
 */
@PlaybackStateCompat.Actions
private long getAvailableActions() {
    long actions = PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
                   | PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
                   | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                   | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS;
    switch (mState) {
        case PlaybackStateCompat.STATE_STOPPED:
            actions |= PlaybackStateCompat.ACTION_PLAY
                       | PlaybackStateCompat.ACTION_PAUSE;
            break;
        case PlaybackStateCompat.STATE_PLAYING:
            actions |= PlaybackStateCompat.ACTION_STOP
                       | PlaybackStateCompat.ACTION_PAUSE
                       | PlaybackStateCompat.ACTION_SEEK_TO;
            break;
        case PlaybackStateCompat.STATE_PAUSED:
            actions |= PlaybackStateCompat.ACTION_PLAY
                       | PlaybackStateCompat.ACTION_STOP;
            break;
        default:
            actions |= PlaybackStateCompat.ACTION_PLAY
                       | PlaybackStateCompat.ACTION_PLAY_PAUSE
                       | PlaybackStateCompat.ACTION_STOP
                       | PlaybackStateCompat.ACTION_PAUSE;
    }
    return actions;
}
 
Example 9
Source File: PlaybackManager.java    From klingar with Apache License 2.0 5 votes vote down vote up
private long getAvailableActions() {
  long actions = PlaybackStateCompat.ACTION_PLAY_PAUSE
      | PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
      | PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
      | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
      | PlaybackStateCompat.ACTION_SKIP_TO_NEXT;
  if (playback.isPlaying()) {
    actions |= PlaybackStateCompat.ACTION_PAUSE;
  } else {
    actions |= PlaybackStateCompat.ACTION_PLAY;
  }
  return actions;
}
 
Example 10
Source File: AudioPlayerService.java    From react-native-streaming-audio-player with MIT License 5 votes vote down vote up
/**
 * Update the current media player state, optionally showing an error message.
 */
public void updatePlaybackState() {
    long position = PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN;
    if (mPlayback != null ) {
        position = mPlayback.getCurrentPosition();
    }
    long actions =
            PlaybackStateCompat.ACTION_PLAY_PAUSE |
            PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
            PlaybackStateCompat.ACTION_SKIP_TO_NEXT;

    if (mPlayback != null && mPlayback.isPlaying()) {
        actions |= PlaybackStateCompat.ACTION_PAUSE;
    } else {
        actions |= PlaybackStateCompat.ACTION_PLAY;
    }

    int state = mPlayback.getState();

    //noinspection ResourceType
    PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
            .setActions(actions)
            .setState(state, position, 1.0f, SystemClock.elapsedRealtime());

    mMediaSession.setPlaybackState(stateBuilder.build());

    Intent intent = new Intent("change-playback-state-event");
    intent.putExtra("state", state);
    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
 
Example 11
Source File: MediaController.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Disable pause or seek buttons if the stream cannot be paused or seeked.
 * This requires the control interface to be a MediaPlayerControlExt
 */
void updateButtons() {
    if (mDelegate == null) return;

    long flags = mDelegate.getActionFlags();
    boolean enabled = isEnabled();
    if (mPauseButton != null) {
        boolean needPlayPauseButton = (flags & PlaybackStateCompat.ACTION_PLAY) != 0
                || (flags & PlaybackStateCompat.ACTION_PAUSE) != 0;
        mPauseButton.setEnabled(enabled && needPlayPauseButton);
    }
    if (mRewButton != null) {
        mRewButton.setEnabled(enabled && (flags & PlaybackStateCompat.ACTION_REWIND) != 0);
    }
    if (mFfwdButton != null) {
        mFfwdButton.setEnabled(
                enabled && (flags & PlaybackStateCompat.ACTION_FAST_FORWARD) != 0);
    }
    if (mPrevButton != null) {
        mShowPrev =
                (flags & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0 || mPrevListener != null;
        mPrevButton.setEnabled(enabled && mShowPrev);
    }
    if (mNextButton != null) {
        mShowNext = (flags & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0
                || mNextListener != null;
        mNextButton.setEnabled(enabled && mShowNext);
    }
}
 
Example 12
Source File: MediaNotificationManager.java    From react-native-streaming-audio-player with MIT License 4 votes vote down vote up
private Notification createNotification() {
    if (mMetadata == null || mPlaybackState == null) {
        return null;
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mService);
    int playPauseButtonPosition = 0;

    // If skip to previous action is enabled
    if ((mPlaybackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0) {
        notificationBuilder.addAction(R.drawable.ic_skip_previous_white_24dp, "previous", mPreviousIntent);

        // If there is a "skip to previous" button, the play/pause button will
        // be the second one. We need to keep track of it, because the MediaStyle notification
        // requires to specify the index of the buttons (actions) that should be visible
        // when in compact view.
        playPauseButtonPosition = 1;
    }

    addPlayPauseAction(notificationBuilder);

    // If skip to next action is enabled
    if ((mPlaybackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
        notificationBuilder.addAction(R.drawable.ic_skip_next_white_24dp, "next", mNextIntent);
    }

    MediaDescriptionCompat description = mMetadata.getDescription();

    String fetchArtUrl = null;
    Bitmap art = null;
    if (description.getIconUri() != null) {
        // This sample assumes the iconUri will be a valid URL formatted String, but
        // it can actually be any valid Android Uri formatted String.
        // async fetch the album art icon
        String artUrl = description.getIconUri().toString();
        art = AlbumArtCache.getInstance().getBigImage(artUrl);
        if (art == null) {
            fetchArtUrl = artUrl;
            // use a placeholder art while the remote art is being downloaded
            art = BitmapFactory.decodeResource(mService.getResources(),
                R.drawable.ic_default_art);
        }
    }

    // Basically we use notification icon but it doesn't exist we use launcher icon
    Context context = mService.getApplicationContext();
    int resId = context.getResources().getIdentifier("ic_notification", "drawable", context.getPackageName());
    if (resId == 0){
        resId = context.getResources().getIdentifier("ic_launcher", "mipmap", context.getPackageName());
    }

    notificationBuilder
            .setStyle(new NotificationCompat.MediaStyle()
                .setShowActionsInCompactView(new int[]{playPauseButtonPosition})  // show only play/pause in compact view
                .setMediaSession(mSessionToken))
            .setColor(0xffdf533b)
            .setSmallIcon(resId)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setUsesChronometer(true)
            .setContentTitle(description.getTitle())
            .setContentText(description.getSubtitle())
            .setLargeIcon(art);

    setNotificationPlaybackState(notificationBuilder);

    // We should get MainActivity.class to set pendingIntent
    // If there exists better way, it should place this logic
    String packageName = mService.getApplicationContext().getPackageName();
    Intent launchIntent = mService.getApplicationContext().getPackageManager().getLaunchIntentForPackage(packageName);
    String className = launchIntent.getComponent().getClassName();

    try {
        Class activityClass = Class.forName(className);
        notificationBuilder.setContentIntent(createContentIntent(activityClass));
    } catch(Exception e) {
        // do nothing
    }

    if (fetchArtUrl != null) {
        fetchBitmapFromURLAsync(fetchArtUrl, notificationBuilder);
    }

    return notificationBuilder.build();
}
 
Example 13
Source File: MediaNotificationManager.java    From LyricHere with Apache License 2.0 4 votes vote down vote up
private Notification createNotification() {
    LogUtils.d(TAG, "updateNotificationMetadata. mMetadata=" + mMetadata);
    if (mMetadata == null || mPlaybackState == null) {
        return null;
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mService);
    int playPauseButtonPosition = 0;

    // If skip to previous action is enabled
    if ((mPlaybackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0) {
        notificationBuilder.addAction(R.drawable.ic_skip_previous_white_24dp,
                mService.getString(R.string.label_previous), mPreviousIntent);

        // If there is a "skip to previous" button, the play/pause button will
        // be the second one. We need to keep track of it, because the MediaStyle notification
        // requires to specify the index of the buttons (actions) that should be visible
        // when in compact view.
        playPauseButtonPosition = 1;
    }

    addPlayPauseAction(notificationBuilder);

    // If skip to next action is enabled
    if ((mPlaybackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
        notificationBuilder.addAction(R.drawable.ic_skip_next_white_24dp,
                mService.getString(R.string.label_next), mNextIntent);
    }

    MediaDescriptionCompat description = mMetadata.getDescription();

    String fetchArtUrl = null;
    Bitmap art = null;
    if (description.getIconUri() != null) {
        // This sample assumes the iconUri will be a valid URL formatted String, but
        // it can actually be any valid Android Uri formatted String.
        // async fetch the album art icon
        String artUrl = description.getIconUri().toString();
        art = AlbumArtCache.getInstance().getBigImage(artUrl);
        if (art == null || art.isRecycled()) {
            fetchArtUrl = artUrl;
            // use a placeholder art while the remote art is being downloaded
            art = BitmapFactory.decodeResource(mService.getResources(), R.drawable.ic_default_art);
        }
    }

    notificationBuilder
            .setStyle(new NotificationCompat.MediaStyle()
                    .setShowActionsInCompactView(
                            new int[]{playPauseButtonPosition})  // show only play/pause in compact view
                    .setMediaSession(mSessionToken))
            .setColor(mNotificationColor)
            .setSmallIcon(R.drawable.ic_notification)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setUsesChronometer(true)
            .setContentIntent(createContentIntent(description))
            .setContentTitle(description.getTitle())
            .setContentText(description.getSubtitle())
            .setLargeIcon(art);

    if (mController != null && mController.getExtras() != null) {
        String castName = mController.getExtras().getString(MusicService.EXTRA_CONNECTED_CAST);
        if (castName != null) {
            String castInfo = mService.getResources()
                    .getString(R.string.casting_to_device, castName);
            notificationBuilder.setSubText(castInfo);
            notificationBuilder.addAction(R.drawable.ic_close_black_24dp,
                    mService.getString(R.string.stop_casting), mStopCastIntent);
        }
    }

    setNotificationPlaybackState(notificationBuilder);
    if (fetchArtUrl != null) {
        fetchBitmapFromURLAsync(fetchArtUrl, notificationBuilder);
    }

    return notificationBuilder.build();
}
 
Example 14
Source File: MediaNotificationManager.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
private Notification createNotification()
    {
        LogHelper.d(TAG, "updateNotificationMetadata. currentYouTubeVideo=" + currentYouTubeVideo);
        if (currentYouTubeVideo == null || playbackState == null) {
            return null;
        }

        Intent clickIntent = new Intent(exoAudioService, MainActivity.class);
        clickIntent.setAction(Intent.ACTION_MAIN);
        clickIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent clickPendingIntent = PendingIntent.getActivity(exoAudioService, 0, clickIntent, 0);

        // Notification channels are only supported on Android O+.
        if (shouldCreateNowRunningChannel()) {
            createNotificationChannel();
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(exoAudioService, CHANNEL_ID);
        int playPauseButtonPosition = 0;

        // If skip to previous action is enabled
        if ((playbackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0) {
            notificationBuilder.addAction(
                    R.drawable.ic_skip_previous_white_24dp,
                    exoAudioService.getString(R.string.action_previous), previousIntent
            );

            // If there is a "skip to previous" button, the play/pause button will
            // be the second one. We need to keep track of it, because the MediaStyle notification
            // requires to specify the index of the buttons (actions) that should be visible
            // when in compact view.
            playPauseButtonPosition = 1;
        }

        addPlayPauseAction(notificationBuilder);

        // If skip to next action is enabled
        if ((playbackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
            notificationBuilder.addAction(
                    R.drawable.ic_skip_next_white_24dp,
                    exoAudioService.getString(R.string.action_next),
                    nextIntent
            );
        }

        // show only play/pause in compact view
        MediaStyle mediaStyle = new MediaStyle()
                .setCancelButtonIntent(stopPendingIntent)
                .setMediaSession(sessionToken)
                .setShowActionsInCompactView(playPauseButtonPosition)
                .setShowCancelButton(true);

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

        setNotificationPlaybackState(notificationBuilder);

        //load bitmap
        if (currentYouTubeVideo.getThumbnailURL() != null && !currentYouTubeVideo.getThumbnailURL().isEmpty()) {
            target.setNotificationBuilder(notificationBuilder);
            Picasso.with(exoAudioService)
                    .load(currentYouTubeVideo.getThumbnailURL())
                    .resize(Config.MAX_WIDTH_ICON, Config.MAX_HEIGHT_ICON)
                    .centerCrop()
                    .into(target);
        }
        return notificationBuilder.build();
    }
 
Example 15
Source File: NotificationBuilder.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
private boolean isSkipToPreviousEnabled()
{
    return (playbackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0;
}
 
Example 16
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 17
Source File: PlayerMediaPlayer.java    From blade-player with GNU General Public License v3.0 4 votes vote down vote up
public PlaybackStateCompat getPlaybackState()
{
    long actions = PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
            | PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
            | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
            | PlaybackStateCompat.ACTION_SET_REPEAT_MODE
            | PlaybackStateCompat.ACTION_SET_SHUFFLE_MODE;

    int playbackState = 0;
    switch(currentState)
    {
        case PLAYER_STATE_PAUSED:
            actions |= PlaybackStateCompat.ACTION_PLAY
                    | PlaybackStateCompat.ACTION_STOP
                    | PlaybackStateCompat.ACTION_SEEK_TO;
            playbackState = PlaybackStateCompat.STATE_PAUSED;
            break;

        case PLAYER_STATE_PLAYING:
            actions |= PlaybackStateCompat.ACTION_PAUSE
                    | PlaybackStateCompat.ACTION_STOP
                    | PlaybackStateCompat.ACTION_SEEK_TO;
            playbackState = PlaybackStateCompat.STATE_PLAYING;
            break;

        case PLAYER_STATE_STOPPED:
            actions |= PlaybackStateCompat.ACTION_PLAY
                    | PlaybackStateCompat.ACTION_PAUSE;
            playbackState = PlaybackStateCompat.STATE_STOPPED;
            break;

        case PLAYER_STATE_NONE:
            actions |= PlaybackStateCompat.ACTION_PLAY
                    | PlaybackStateCompat.ACTION_PAUSE;
            playbackState = PlaybackStateCompat.STATE_STOPPED;
            break;

        case PLAYER_STATE_DO_NOTHING:
            actions |= PlaybackStateCompat.ACTION_PLAY
                    | PlaybackStateCompat.ACTION_PAUSE;
            playbackState = PlaybackStateCompat.STATE_STOPPED;
    }

    final PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder();
    stateBuilder.setActions(actions);
    stateBuilder.setState(playbackState, getCurrentPosition(), 1.0f, SystemClock.elapsedRealtime());
    return stateBuilder.build();
}
 
Example 18
Source File: MediaNotificationManager.java    From react-native-audio-streaming-player with MIT License 4 votes vote down vote up
private Notification createNotification() {
    if (mMetadata == null || mPlaybackState == null) {
        return null;
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mService);
    int playPauseButtonPosition = 0;

    // If skip to previous action is enabled
    if ((mPlaybackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0) {
        notificationBuilder.addAction(R.drawable.ic_skip_previous_white_24dp, "previous", mPreviousIntent);

        // If there is a "skip to previous" button, the play/pause button will
        // be the second one. We need to keep track of it, because the MediaStyle notification
        // requires to specify the index of the buttons (actions) that should be visible
        // when in compact view.
        playPauseButtonPosition = 1;
    }

    addPlayPauseAction(notificationBuilder);

    // If skip to next action is enabled
    if ((mPlaybackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
        notificationBuilder.addAction(R.drawable.ic_skip_next_white_24dp, "next", mNextIntent);
    }

    MediaDescriptionCompat description = mMetadata.getDescription();

    String fetchArtUrl = null;
    Bitmap art = null;
    if (description.getIconUri() != null) {
        // This sample assumes the iconUri will be a valid URL formatted String, but
        // it can actually be any valid Android Uri formatted String.
        // async fetch the album art icon
        String artUrl = description.getIconUri().toString();
        art = AlbumArtCache.getInstance().getBigImage(artUrl);
        if (art == null) {
            fetchArtUrl = artUrl;
            // use a placeholder art while the remote art is being downloaded
            art = BitmapFactory.decodeResource(mService.getResources(),
                R.drawable.ic_default_art);
        }
    }

    // Basically we use notification icon but it doesn't exist we use launcher icon
    Context context = mService.getApplicationContext();
    int resId = context.getResources().getIdentifier("ic_notification", "drawable", context.getPackageName());
    if (resId == 0){
        resId = context.getResources().getIdentifier("ic_launcher", "mipmap", context.getPackageName());
    }

    notificationBuilder
            .setStyle(new NotificationCompat.MediaStyle()
                .setShowActionsInCompactView(new int[]{playPauseButtonPosition})  // show only play/pause in compact view
                .setMediaSession(mSessionToken))
            .setColor(0xffdf533b)
            .setSmallIcon(resId)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setUsesChronometer(true)
            .setContentTitle(description.getTitle())
            .setContentText(description.getSubtitle())
            .setLargeIcon(art);

    setNotificationPlaybackState(notificationBuilder);

    // We should get MainActivity.class to set pendingIntent
    // If there exists better way, it should place this logic
    String packageName = mService.getApplicationContext().getPackageName();
    Intent launchIntent = mService.getApplicationContext().getPackageManager().getLaunchIntentForPackage(packageName);
    String className = launchIntent.getComponent().getClassName();

    try {
        Class activityClass = Class.forName(className);
        notificationBuilder.setContentIntent(createContentIntent(activityClass));
    } catch(Exception e) {
        // do nothing
    }

    if (fetchArtUrl != null) {
        fetchBitmapFromURLAsync(fetchArtUrl, notificationBuilder);
    }

    return notificationBuilder.build();
}
 
Example 19
Source File: NotificationWrapper.java    From react-native-jw-media-player with MIT License 4 votes vote down vote up
public Notification createNotification(Context context,
                                          MediaSessionCompat mediaSession,
                                          long capabilities
) {
	int appIcon = context.getResources().getIdentifier("ic_app_icon", "drawable", context.getPackageName());

	// Media metadata
	MediaControllerCompat controller = mediaSession.getController();
	MediaMetadataCompat mediaMetadata = controller.getMetadata();
	MediaDescriptionCompat description = mediaMetadata.getDescription();

	// Notification
	NotificationCompat.Builder builder = new NotificationCompat.Builder(context,
																		NOTIFICATION_CHANNEL_ID);
	builder.setContentTitle(description.getTitle())
		   .setContentText(description.getSubtitle())
		   .setSubText(description.getDescription())
		   .setLargeIcon(description.getIconBitmap())
		   .setOnlyAlertOnce(true)
		   .setStyle(new MediaStyle()
				   .setMediaSession(mediaSession.getSessionToken())
				   .setShowActionsInCompactView(0))
		   .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
		   .setSmallIcon(appIcon > 0 ? appIcon : R.drawable.ic_jw_developer)
		   .setDeleteIntent(getActionIntent(context, KeyEvent.KEYCODE_MEDIA_STOP));


	// Attach actions to the notification.
	if ((capabilities & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0) {
		builder.addAction(R.drawable.ic_previous, "Previous",
						  getActionIntent(context,
										  KeyEvent.KEYCODE_MEDIA_PREVIOUS));
	}
	if ((capabilities & PlaybackStateCompat.ACTION_PAUSE) != 0) {
		builder.addAction(R.drawable.ic_pause, "Pause",
						  getActionIntent(context,
										  KeyEvent.KEYCODE_MEDIA_PAUSE));
	}
	if ((capabilities & PlaybackStateCompat.ACTION_PLAY) != 0) {
		builder.addAction(R.drawable.ic_play, "Play",
						  getActionIntent(context,
										  KeyEvent.KEYCODE_MEDIA_PLAY)
		);
	}
	if ((capabilities & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
		builder.addAction(R.drawable.ic_next, "Next",
						  getActionIntent(context,
										  KeyEvent.KEYCODE_MEDIA_NEXT));
	}

	// We want to resume the existing VideoActivity, over creating a new one.
	Intent intent = new Intent(context, context.getClass());
	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
	builder.setContentIntent(pendingIntent);

	Notification notification = builder.build();

	mNotificationManager.notify(NOTIFICATION_ID, notification);

	return notification;
}
 
Example 20
Source File: MusicPlaybackService.java    From leanback-showcase with Apache License 2.0 2 votes vote down vote up
/**
 * @return The available set of actions for the media session. These actions should be provided
 * for the MediaSession PlaybackState in order for
 * {@link MediaSessionCompat.Callback#onMediaButtonEvent} to call relevant methods of onPause() or
 * onPlay().
 */
private long getPlaybackStateActions() {
    return PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE |
            PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS;
}