Java Code Examples for android.media.session.PlaybackState#STATE_PLAYING

The following examples show how to use android.media.session.PlaybackState#STATE_PLAYING . 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: PlaybackOverlayFragment.java    From BuildingForAndroidTV with MIT License 6 votes vote down vote up
@Override
public void onPlaybackStateChanged(PlaybackState state) {
    Log.d(TAG, "playback state changed: " + state.getState());
    if (state.getState() == PlaybackState.STATE_PLAYING && mCurrentPlaybackState != PlaybackState.STATE_PLAYING) {
        mCurrentPlaybackState = PlaybackState.STATE_PLAYING;
        startProgressAutomation();
        setFadingEnabled(true);
        mPlayPauseAction.setIndex(PlayPauseAction.PAUSE);
        mPlayPauseAction.setIcon(mPlayPauseAction.getDrawable(PlayPauseAction.PAUSE));
        notifyChanged(mPlayPauseAction);
    } else if (state.getState() == PlaybackState.STATE_PAUSED && mCurrentPlaybackState != PlaybackState.STATE_PAUSED) {
        mCurrentPlaybackState = PlaybackState.STATE_PAUSED;
        stopProgressAutomation();
        setFadingEnabled(false);
        mPlayPauseAction.setIndex(PlayPauseAction.PLAY);
        mPlayPauseAction.setIcon(mPlayPauseAction.getDrawable(PlayPauseAction.PLAY));
        notifyChanged(mPlayPauseAction);
    }

    int currentTime = (int)state.getPosition();
    mPlaybackControlsRow.setCurrentTime(currentTime);
    mPlaybackControlsRow.setBufferedProgress(currentTime + SIMULATED_BUFFERED_TIME);
}
 
Example 2
Source File: MusicPlayerActivity.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    MediaBrowser.MediaItem item = getItem(position);
    int itemState = MediaItemViewHolder.STATE_NONE;
    if (item.isPlayable()) {
        String itemMediaId = item.getDescription().getMediaId();
        int playbackState = PlaybackState.STATE_NONE;
        if (mCurrentState != null) {
            playbackState = mCurrentState.getState();
        }
        if (mCurrentMetadata != null &&
                itemMediaId.equals(mCurrentMetadata.getDescription().getMediaId())) {
            if (playbackState == PlaybackState.STATE_PLAYING ||
                playbackState == PlaybackState.STATE_BUFFERING) {
                itemState = MediaItemViewHolder.STATE_PLAYING;
            } else if (playbackState != PlaybackState.STATE_ERROR) {
                itemState = MediaItemViewHolder.STATE_PAUSED;
            }
        }
    }
    return MediaItemViewHolder.setupView((Activity) getContext(), convertView, parent,
        item.getDescription(), itemState);
}
 
Example 3
Source File: MusicPlayerActivity.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    MediaBrowser.MediaItem item = getItem(position);
    int itemState = MediaItemViewHolder.STATE_NONE;
    if (item.isPlayable()) {
        String itemMediaId = item.getDescription().getMediaId();
        int playbackState = PlaybackState.STATE_NONE;
        if (mCurrentState != null) {
            playbackState = mCurrentState.getState();
        }
        if (mCurrentMetadata != null &&
                itemMediaId.equals(mCurrentMetadata.getDescription().getMediaId())) {
            if (playbackState == PlaybackState.STATE_PLAYING ||
                playbackState == PlaybackState.STATE_BUFFERING) {
                itemState = MediaItemViewHolder.STATE_PLAYING;
            } else if (playbackState != PlaybackState.STATE_ERROR) {
                itemState = MediaItemViewHolder.STATE_PAUSED;
            }
        }
    }
    return MediaItemViewHolder.setupView((Activity) getContext(), convertView, parent,
        item.getDescription(), itemState);
}
 
Example 4
Source File: PlayerState.java    From scroball with MIT License 6 votes vote down vote up
public void setPlaybackState(PlaybackState playbackState) {
  if (playbackItem == null) {
    return;
  }

  playbackItem.updateAmountPlayed();

  int state = playbackState.getState();
  boolean isPlaying = state == PlaybackState.STATE_PLAYING;

  if (isPlaying) {
    Log.d(TAG, "Track playing");
    postEvent(playbackItem.getTrack());
    playbackItem.startPlaying();
    notificationManager.updateNowPlaying(playbackItem.getTrack());
    scheduleSubmission();
  } else {
    Log.d(TAG, String.format("Track paused (state %d)", state));
    postEvent(Track.empty());
    playbackItem.stopPlaying();
    notificationManager.removeNowPlaying();
    scrobbler.submit(playbackItem);
  }
}
 
Example 5
Source File: MediaPlayback.java    From PodEmu with GNU General Public License v3.0 6 votes vote down vote up
public void action_play_pause()
{
    PodEmuLog.debug("PEMP: action PLAY_PAUSE requested");
    MediaController mediaController=getActiveMediaController();
    if( mediaController!=null && mediaController.getPlaybackState()!=null && mediaController.getTransportControls()!=null)// && (mediaController.getPlaybackState().getActions() & PlaybackState.ACTION_PLAY_PAUSE) == PlaybackState.ACTION_PLAY_PAUSE)
    {
        PodEmuLog.debug("PEMP: executing action through MediaController (ACTION_PLAY_PAUSE)");
        if(mediaController.getPlaybackState().getState() == PlaybackState.STATE_PLAYING)
            mediaController.getTransportControls().pause();
        else
            mediaController.getTransportControls().play();
    }
    else
    {
        PodEmuLog.debug("PEMP: executing action through KeyEvent");
        execute_action(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
    }
}
 
Example 6
Source File: MusicBrowserService.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
private void updatePlaybackState(String error) {
    long position = PlaybackState.PLAYBACK_POSITION_UNKNOWN;
    MessageObject playingMessageObject = MediaController.getInstance().getPlayingMessageObject();
    if (playingMessageObject != null) {
        position = playingMessageObject.audioProgressSec * 1000L;
    }

    PlaybackState.Builder stateBuilder = new PlaybackState.Builder().setActions(getAvailableActions());
    int state;
    if (playingMessageObject == null) {
        state = PlaybackState.STATE_STOPPED;
    } else {
        if (MediaController.getInstance().isDownloadingCurrentMessage()) {
            state = PlaybackState.STATE_BUFFERING;
        } else {
            state = MediaController.getInstance().isMessagePaused() ? PlaybackState.STATE_PAUSED : PlaybackState.STATE_PLAYING;
        }
    }

    if (error != null) {
        stateBuilder.setErrorMessage(error);
        state = PlaybackState.STATE_ERROR;
    }
    stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());
    if (playingMessageObject != null) {
        stateBuilder.setActiveQueueItemId(MediaController.getInstance().getPlayingMessageObjectNum());
    } else {
        stateBuilder.setActiveQueueItemId(0);
    }

    mediaSession.setPlaybackState(stateBuilder.build());
}
 
Example 7
Source File: MediaController2Lollipop.java    From AcDisplay with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void sendMediaAction(int action) {
    if (mMediaController == null) {
        // Maybe somebody is waiting to start his player by
        // this lovely event.
        // TODO: Check if it works as expected.
        MediaController2.broadcastMediaAction(mContext, action);
        return;
    }

    MediaController.TransportControls controls = mMediaController.getTransportControls();
    switch (action) {
        case ACTION_PLAY_PAUSE:
            if (mPlaybackState == PlaybackState.STATE_PLAYING) {
                controls.pause();
            } else {
                controls.play();
            }
            break;
        case ACTION_STOP:
            controls.stop();
            break;
        case ACTION_SKIP_TO_NEXT:
            controls.skipToNext();
            break;
        case ACTION_SKIP_TO_PREVIOUS:
            controls.skipToPrevious();
            break;
        default:
            throw new IllegalArgumentException();
    }
}
 
Example 8
Source File: PlaybackManager.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Called by AudioManager on audio focus changes.
 * Implementation of {@link AudioManager.OnAudioFocusChangeListener}
 */
@Override
public void onAudioFocusChange(int focusChange) {
    boolean gotFullFocus = false;
    boolean canDuck = false;
    if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        gotFullFocus = true;

    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        // We have lost focus. If we can duck (low playback volume), we can keep playing.
        // Otherwise, we need to pause the playback.
        canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
    }

    if (gotFullFocus || canDuck) {
        if (mMediaPlayer != null) {
            if (mPlayOnFocusGain) {
                mPlayOnFocusGain = false;
                mMediaPlayer.start();
                mState = PlaybackState.STATE_PLAYING;
                updatePlaybackState();
            }
            float volume = canDuck ? 0.2f : 1.0f;
            mMediaPlayer.setVolume(volume, volume);
        }
    } else if (mState == PlaybackState.STATE_PLAYING) {
        mMediaPlayer.pause();
        mState = PlaybackState.STATE_PAUSED;
        updatePlaybackState();
    }
}
 
Example 9
Source File: PlaybackManager.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Called by AudioManager on audio focus changes.
 * Implementation of {@link AudioManager.OnAudioFocusChangeListener}
 */
@Override
public void onAudioFocusChange(int focusChange) {
    boolean gotFullFocus = false;
    boolean canDuck = false;
    if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        gotFullFocus = true;

    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        // We have lost focus. If we can duck (low playback volume), we can keep playing.
        // Otherwise, we need to pause the playback.
        canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
    }

    if (gotFullFocus || canDuck) {
        if (mMediaPlayer != null) {
            if (mPlayOnFocusGain) {
                mPlayOnFocusGain = false;
                mMediaPlayer.start();
                mState = PlaybackState.STATE_PLAYING;
                updatePlaybackState();
            }
            float volume = canDuck ? 0.2f : 1.0f;
            mMediaPlayer.setVolume(volume, volume);
        }
    } else if (mState == PlaybackState.STATE_PLAYING) {
        mMediaPlayer.pause();
        mState = PlaybackState.STATE_PAUSED;
        updatePlaybackState();
    }
}
 
Example 10
Source File: PlaybackActivity.java    From BuildingForAndroidTV with MIT License 5 votes vote down vote up
private void updatePlaybackState() {
    PlaybackState.Builder stateBuilder = new PlaybackState.Builder()
            .setActions(getAvailableActions());
    int state = PlaybackState.STATE_PLAYING;
    if (mPlaybackState == LeanbackPlaybackState.PAUSED || mPlaybackState == LeanbackPlaybackState.IDLE) {
        state = PlaybackState.STATE_PAUSED;
    }
    stateBuilder.setState(state, mVideoView.getCurrentPosition(), 1.0f);
    mSession.setPlaybackState(stateBuilder.build());
}
 
Example 11
Source File: MediaSessionRecord.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private PlaybackState getStateWithUpdatedPosition() {
    PlaybackState state;
    long duration = -1;
    synchronized (mLock) {
        state = mPlaybackState;
        if (mMetadata != null && mMetadata.containsKey(MediaMetadata.METADATA_KEY_DURATION)) {
            duration = mMetadata.getLong(MediaMetadata.METADATA_KEY_DURATION);
        }
    }
    PlaybackState result = null;
    if (state != null) {
        if (state.getState() == PlaybackState.STATE_PLAYING
                || state.getState() == PlaybackState.STATE_FAST_FORWARDING
                || state.getState() == PlaybackState.STATE_REWINDING) {
            long updateTime = state.getLastPositionUpdateTime();
            long currentTime = SystemClock.elapsedRealtime();
            if (updateTime > 0) {
                long position = (long) (state.getPlaybackSpeed()
                        * (currentTime - updateTime)) + state.getPosition();
                if (duration >= 0 && position > duration) {
                    position = duration;
                } else if (position < 0) {
                    position = 0;
                }
                PlaybackState.Builder builder = new PlaybackState.Builder(state);
                builder.setState(state.getState(), position, state.getPlaybackSpeed(),
                        currentTime);
                result = builder.build();
            }
        }
    }
    return result == null ? state : result;
}
 
Example 12
Source File: PlaybackManager.java    From android-music-player with Apache License 2.0 5 votes vote down vote up
/**
 * Called by AudioManager on audio focus changes.
 * Implementation of {@link AudioManager.OnAudioFocusChangeListener}
 */
@Override
public void onAudioFocusChange(int focusChange) {
    boolean gotFullFocus = false;
    boolean canDuck = false;
    if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        gotFullFocus = true;

    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        // We have lost focus. If we can duck (low playback volume), we can keep playing.
        // Otherwise, we need to pause the playback.
        canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
    }

    if (gotFullFocus || canDuck) {
        if (mMediaPlayer != null) {
            if (mPlayOnFocusGain) {
                mPlayOnFocusGain = false;
                mMediaPlayer.start();
                mState = PlaybackState.STATE_PLAYING;
                updatePlaybackState();
            }
            float volume = canDuck ? 0.2f : 1.0f;
            mMediaPlayer.setVolume(volume, volume);
        }
    } else if (mState == PlaybackState.STATE_PLAYING) {
        mMediaPlayer.pause();
        mState = PlaybackState.STATE_PAUSED;
        updatePlaybackState();
    }
}
 
Example 13
Source File: MediaService.java    From AsteroidOSSync with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onPlaybackStateChanged(@NonNull PlaybackState state) {
    super.onPlaybackStateChanged(state);
    byte[] data = new byte[1];
    data[0] = (byte)(state.getState() == PlaybackState.STATE_PLAYING ?  1 : 0);
    mDevice.write(mediaPlayingCharac, data, MediaService.this);
}
 
Example 14
Source File: MusicBrowserService.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
private void updatePlaybackState(String error) {
    long position = PlaybackState.PLAYBACK_POSITION_UNKNOWN;
    MessageObject playingMessageObject = MediaController.getInstance().getPlayingMessageObject();
    if (playingMessageObject != null) {
        position = playingMessageObject.audioProgressSec * 1000L;
    }

    PlaybackState.Builder stateBuilder = new PlaybackState.Builder().setActions(getAvailableActions());
    int state;
    if (playingMessageObject == null) {
        state = PlaybackState.STATE_STOPPED;
    } else {
        if (MediaController.getInstance().isDownloadingCurrentMessage()) {
            state = PlaybackState.STATE_BUFFERING;
        } else {
            state = MediaController.getInstance().isMessagePaused() ? PlaybackState.STATE_PAUSED : PlaybackState.STATE_PLAYING;
        }
    }

    if (error != null) {
        stateBuilder.setErrorMessage(error);
        state = PlaybackState.STATE_ERROR;
    }
    stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());
    if (playingMessageObject != null) {
        stateBuilder.setActiveQueueItemId(MediaController.getInstance().getPlayingMessageObjectNum());
    } else {
        stateBuilder.setActiveQueueItemId(0);
    }

    mediaSession.setPlaybackState(stateBuilder.build());
}
 
Example 15
Source File: WebViewCarFragment.java    From carstream-android-auto with Apache License 2.0 5 votes vote down vote up
@Override
public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
    super.onUnhandledKeyEvent(view, event);
    if (event.getAction() == KeyEvent.ACTION_UP) {
        if (warningScreenOpen && event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER) {
            onReadyToExitSafetyInstructions(null);
        } else {
            if (webView.isVideoFullscreen()) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {
                    showToolbar();
                    showCornerControls();
                    cornerControls.requestFocus(View.FOCUS_UP);
                } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
                    cornerControls.clearFocus();
                    hideToolbar();
                    hideCornerControls(true);
                } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER) {
                    if (playerState == PlaybackState.STATE_PLAYING) {
                        webView.pauseVideo();
                    } else {
                        webView.playVideo();
                    }
                } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
                    webView.seekBySeconds(+10);
                } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
                    webView.seekBySeconds(-10);
                }
            }
        }
    }
}
 
Example 16
Source File: WebViewCarFragment.java    From carstream-android-auto with Apache License 2.0 5 votes vote down vote up
@Override
public void onStop() {
    if (playerState == PlaybackState.STATE_PLAYING) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                resumePlayback();
            }
        }, 200);
    }
    super.onStop();
}
 
Example 17
Source File: MusicBrowserService.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private void updatePlaybackState(String error) {
    long position = PlaybackState.PLAYBACK_POSITION_UNKNOWN;
    MessageObject playingMessageObject = MediaController.getInstance().getPlayingMessageObject();
    if (playingMessageObject != null) {
        position = playingMessageObject.audioProgressSec * 1000;
    }

    PlaybackState.Builder stateBuilder = new PlaybackState.Builder().setActions(getAvailableActions());
    int state;
    if (playingMessageObject == null) {
        state = PlaybackState.STATE_STOPPED;
    } else {
        if (MediaController.getInstance().isDownloadingCurrentMessage()) {
            state = PlaybackState.STATE_BUFFERING;
        } else {
            state = MediaController.getInstance().isMessagePaused() ? PlaybackState.STATE_PAUSED : PlaybackState.STATE_PLAYING;
        }
    }

    if (error != null) {
        stateBuilder.setErrorMessage(error);
        state = PlaybackState.STATE_ERROR;
    }
    stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());
    if (playingMessageObject != null) {
        stateBuilder.setActiveQueueItemId(MediaController.getInstance().getPlayingMessageObjectNum());
    } else {
        stateBuilder.setActiveQueueItemId(0);
    }

    mediaSession.setPlaybackState(stateBuilder.build());
}
 
Example 18
Source File: MediaNotificationManager.java    From android-music-player with Apache License 2.0 4 votes vote down vote up
public void update(MediaMetadata metadata, PlaybackState state, MediaSession.Token token) {
    if (state == null || state.getState() == PlaybackState.STATE_STOPPED ||
            state.getState() == PlaybackState.STATE_NONE) {
        mService.stopForeground(true);
        try {
            mService.unregisterReceiver(this);
        } catch (IllegalArgumentException ex) {
            // ignore receiver not registered
        }
        mService.stopSelf();
        return;
    }
    if (metadata == null) {
        return;
    }
    boolean isPlaying = state.getState() == PlaybackState.STATE_PLAYING;
    Notification.Builder notificationBuilder = new Notification.Builder(mService);
    MediaDescription description = metadata.getDescription();

    notificationBuilder
            .setStyle(new Notification.MediaStyle()
                    .setMediaSession(token)
                    .setShowActionsInCompactView(0, 1, 2))
            .setColor(mService.getApplication().getResources().getColor(R.color.notification_bg))
            .setSmallIcon(R.drawable.ic_notification)
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setContentIntent(createContentIntent())
            .setContentTitle(description.getTitle())
            .setContentText(description.getSubtitle())
            .setLargeIcon(MusicLibrary.getAlbumBitmap(mService, description.getMediaId()))
            .setOngoing(isPlaying)
            .setWhen(isPlaying ? System.currentTimeMillis() - state.getPosition() : 0)
            .setShowWhen(isPlaying)
            .setUsesChronometer(isPlaying);

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

    notificationBuilder.addAction(isPlaying ? mPauseAction : mPlayAction);

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

    Notification notification = notificationBuilder.build();

    if (isPlaying && !mStarted) {
        mService.startService(new Intent(mService.getApplicationContext(), MusicService.class));
        mService.startForeground(NOTIFICATION_ID, notification);
        mStarted = true;
    } else {
        if (!isPlaying) {
            mService.stopForeground(false);
            mStarted = false;
        }
        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }
}
 
Example 19
Source File: MediaControllerCallback.java    From QuickLyric with GNU General Public License v3.0 4 votes vote down vote up
public void registerActiveSessionCallback(Context context, List<MediaController> controllers) {
    if (controllers.size() > 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        controller = controllers.get(0);
        sController = new WeakReference<>(controller);
        if (controllerCallback != null) {
            for (MediaController ctlr : controllers)
                ctlr.unregisterCallback(controllerCallback);
        } else {
            controllerCallback = new MediaController.Callback() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void onPlaybackStateChanged(PlaybackState state) {
                    super.onPlaybackStateChanged(state);
                    if (state == null)
                        return;
                    if (isInvalidPackage(controller))
                        return;
                    boolean isPlaying = state.getState() == PlaybackState.STATE_PLAYING;
                    if (!isPlaying) {
                        NotificationManager notificationManager =
                                ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE));
                        notificationManager.cancel(0);
                        notificationManager.cancel(8);
                    }
                    savePlayerName(controller.getPackageName(), context);
                    if (controller != controller)
                        return; //ignore inactive sessions
                    broadcastControllerState(context, controller, isPlaying);
                }

                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void onMetadataChanged(MediaMetadata metadata) {
                    super.onMetadataChanged(metadata);
                    if (controller != controller)
                        return;
                    if (metadata == null)
                        return;
                    if (isInvalidPackage(controller))
                        return;
                    savePlayerName(controller.getPackageName(), context);
                    broadcastControllerState(context, controller, null);
                }
            };
        }
        controller.registerCallback(controllerCallback);
        if (isInvalidPackage(controller))
            return;
        broadcastControllerState(context, controller, null);
    }
}
 
Example 20
Source File: MediaNotificationManager.java    From io2015-codelabs with Apache License 2.0 4 votes vote down vote up
public void update(MediaMetadata metadata, PlaybackState state, MediaSession.Token token) {
    if (state == null || state.getState() == PlaybackState.STATE_STOPPED ||
            state.getState() == PlaybackState.STATE_NONE) {
        mService.stopForeground(true);
        try {
            mService.unregisterReceiver(this);
        } catch (IllegalArgumentException ex) {
            // ignore receiver not registered
        }
        mService.stopSelf();
        return;
    }
    if (metadata == null) {
        return;
    }
    boolean isPlaying = state.getState() == PlaybackState.STATE_PLAYING;
    Notification.Builder notificationBuilder = new Notification.Builder(mService);
    MediaDescription description = metadata.getDescription();

    notificationBuilder
            .setStyle(new Notification.MediaStyle()
                    .setMediaSession(token)
                    .setShowActionsInCompactView(0, 1, 2))
            .setColor(mService.getApplication().getResources().getColor(R.color.notification_bg))
            .setSmallIcon(R.drawable.ic_notification)
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setContentIntent(createContentIntent())
            .setContentTitle(description.getTitle())
            .setContentText(description.getSubtitle())
            .setLargeIcon(MusicLibrary.getAlbumBitmap(mService, description.getMediaId()))
            .setOngoing(isPlaying)
            .setWhen(isPlaying ? System.currentTimeMillis() - state.getPosition() : 0)
            .setShowWhen(isPlaying)
            .setUsesChronometer(isPlaying);

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

    notificationBuilder.addAction(isPlaying ? mPauseAction : mPlayAction);

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

    Notification notification = notificationBuilder.build();

    if (isPlaying && !mStarted) {
        mService.startService(new Intent(mService.getApplicationContext(), MusicService.class));
        mService.startForeground(NOTIFICATION_ID, notification);
        mStarted = true;
    } else {
        if (!isPlaying) {
            mService.stopForeground(false);
            mStarted = false;
        }
        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }
}