Java Examples for android.support.v4.media.session.PlaybackStateCompat

The following java examples will help you to understand the usage of android.support.v4.media.session.PlaybackStateCompat. These source code samples are taken from different open source projects.

Example 1
Project: GEM-master  File: MainScreen.java View source code
private void setUpNavigation() {
    ///////////////////////
    // Navigation Drawer //
    ///////////////////////
    mNavigationView.setNavigationItemSelectedListener(this);
    PlaybackRemote.registerStateListener(new PlaybackRemote.StateChangedListener() {

        @Override
        public void onStateChanged(PlaybackStateCompat newState) {
            setUpDrawerHeader(null);
        }
    });
    PlaybackRemote.registerSongListener(new PlaybackRemote.SongChangedListener() {

        @Override
        public void onSongChanged(Song newSong) {
            setUpDrawerHeader(newSong);
        }
    });
    if (GEMUtil.isLollipop()) {
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        getWindow().setNavigationBarColor(Color.RED);
    }
    mDrawerLayout.setStatusBarBackgroundColor(getPrimaryDarkColor());
    //////////
    if (!Options.usingTabs()) {
        mPager.lock();
        mTabs.setVisibility(View.GONE);
        return;
    }
    //Makes tabs scrollable or fixed based on setting
    mTabs.setTabMode(Options.usingScrollableTabs() ? TabLayout.MODE_SCROLLABLE : TabLayout.MODE_FIXED);
    if (!Options.usingScrollableTabs())
        mTabs.setPadding(0, 0, 0, 0);
    //Configures and adds tabs
    TabLayout.Tab songsTab, albumsTab, playlistsTab, artistsTab;
    if (!Options.usingIconTabs()) {
        songsTab = mTabs.newTab().setText(R.string.page_songs);
        albumsTab = mTabs.newTab().setText(R.string.page_albums);
        artistsTab = mTabs.newTab().setText(R.string.page_artists);
        playlistsTab = mTabs.newTab().setText(R.string.page_playlists);
    } else {
        songsTab = mTabs.newTab().setIcon(R.drawable.ic_audiotrack_24dp);
        albumsTab = mTabs.newTab().setIcon(R.drawable.ic_album_24dp);
        artistsTab = mTabs.newTab().setIcon(R.drawable.ic_artist_24dp);
        playlistsTab = mTabs.newTab().setIcon(R.drawable.ic_queue_music_black_24dp);
    }
    mTabs.addTab(songsTab);
    mTabs.addTab(albumsTab);
    mTabs.addTab(artistsTab);
    mTabs.addTab(playlistsTab);
    //Allows the tabs to sync to the view pager
    mTabs.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mPager));
    mPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabs));
}
Example 2
Project: Cheerleader-master  File: MediaSessionWrapper.java View source code
/**
     * Propagate the playback state to the media session and the lock screen remote control.
     * <p/>
     * See also :
     * {@link fr.tvbarthel.cheerleader.library.media.MediaSessionWrapper#PLAYBACK_STATE_STOPPED}
     * {@link fr.tvbarthel.cheerleader.library.media.MediaSessionWrapper#PLAYBACK_STATE_PLAYING}
     * {@link fr.tvbarthel.cheerleader.library.media.MediaSessionWrapper#PLAYBACK_STATE_PAUSED}
     *
     * @param state playback state.
     */
@SuppressWarnings("deprecation")
public void setPlaybackState(int state) {
    switch(state) {
        case PLAYBACK_STATE_STOPPED:
            setRemoteControlClientPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
            setMediaSessionCompatPlaybackState(PlaybackStateCompat.STATE_STOPPED);
            mMediaSession.setActive(false);
            break;
        case PLAYBACK_STATE_PLAYING:
            setRemoteControlClientPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
            setMediaSessionCompatPlaybackState(PlaybackStateCompat.STATE_PLAYING);
            mMediaSession.setActive(true);
            break;
        case PLAYBACK_STATE_PAUSED:
            setRemoteControlClientPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED);
            setMediaSessionCompatPlaybackState(PlaybackStateCompat.STATE_PAUSED);
            break;
        default:
            Log.e(TAG, "Unknown playback state.");
            break;
    }
}
Example 3
Project: Sunami-master  File: TheBrain.java View source code
private void setMetadata(FireMixtape song) {
    new GetArtworkTask().execute(song);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mNotification = getLollipopNotifBuilder(true).setLargeIcon(mThumbnail).setContentTitle(song.title).setContentText(song.artist).build();
        startForeground(534, mNotification);
    } else {
        PlaybackStateCompat state = new PlaybackStateCompat.Builder().setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS).setState(PlaybackStateCompat.STATE_PLAYING, 0, 0.0f).build();
        MediaSessionCompatHelper.applyState(mSession, state);
        mSession.setMetadata(new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_TITLE, song.title).putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, song.artist).putLong(MediaMetadata.METADATA_KEY_DURATION, Long.parseLong(song.duration)).build());
    }
}
Example 4
Project: spotify-tv-master  File: MediaPlayerSessionController.java View source code
private void updatePlaybackState(@NonNull PlayerState playerState, @NonNull ContentState contentState) {
    int position = playerState.positionInMs;
    //noinspection WrongConstant
    PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder().setActions(getAvailableActions(playerState, contentState));
    //noinspection WrongConstant
    stateBuilder.setState(getState(playerState), position, 1.0f);
    mNowPlayingSession.setPlaybackState(stateBuilder.build());
}
Example 5
Project: AcDisplay-master  File: MediaWidget.java View source code
@Override
public void onPlaybackStateChanged(int state) {
    // much overkill for me.
    if (state == PlaybackStateCompat.STATE_ERROR) {
        mButtonPlayPause.setImageDrawable(mWarningDrawable);
    } else {
        mButtonPlayPause.setImageDrawable(mPlayPauseDrawable);
    }
    if (DEBUG)
        Log.d(TAG, "Playback state is " + state);
    final int imageDescId;
    switch(state) {
        case PlaybackStateCompat.STATE_ERROR:
            imageDescId = R.string.media_play_description;
            break;
        case PlaybackStateCompat.STATE_PLAYING:
            mPlayPauseDrawable.transformToPause();
            imageDescId = R.string.media_pause_description;
            break;
        case PlaybackStateCompat.STATE_BUFFERING:
        case PlaybackStateCompat.STATE_STOPPED:
            mPlayPauseDrawable.transformToStop();
            imageDescId = R.string.media_stop_description;
            break;
        case PlaybackStateCompat.STATE_PAUSED:
        default:
            mPlayPauseDrawable.transformToPlay();
            imageDescId = R.string.media_play_description;
            break;
    }
    mButtonPlayPause.setContentDescription(getFragment().getString(imageDescId));
}
Example 6
Project: android-sdk-sources-for-api-level-23-master  File: MediaControllerCompat.java View source code
@Override
public void handleMessage(Message msg) {
    if (!mRegistered) {
        return;
    }
    switch(msg.what) {
        case MSG_EVENT:
            onSessionEvent((String) msg.obj, msg.getData());
            break;
        case MSG_UPDATE_PLAYBACK_STATE:
            onPlaybackStateChanged((PlaybackStateCompat) msg.obj);
            break;
        case MSG_UPDATE_METADATA:
            onMetadataChanged((MediaMetadataCompat) msg.obj);
            break;
        case MSG_UPDATE_QUEUE:
            onQueueChanged((List<MediaSessionCompat.QueueItem>) msg.obj);
            break;
        case MSG_UPDATE_QUEUE_TITLE:
            onQueueTitleChanged((CharSequence) msg.obj);
            break;
        case MSG_UPDATE_EXTRAS:
            onExtrasChanged((Bundle) msg.obj);
            break;
        case MSG_UPDATE_VOLUME:
            onAudioInfoChanged((PlaybackInfo) msg.obj);
            break;
        case MSG_DESTROYED:
            onSessionDestroyed();
            break;
    }
}
Example 7
Project: android-UniversalMusicPlayer-master  File: LocalPlayback.java View source code
@Override
public void stop(boolean notifyListeners) {
    mState = PlaybackStateCompat.STATE_STOPPED;
    if (notifyListeners && mCallback != null) {
        mCallback.onPlaybackStatusChanged(mState);
    }
    mCurrentPosition = getCurrentStreamPosition();
    // Give up Audio focus
    giveUpAudioFocus();
    unregisterAudioNoisyReceiver();
    // Relax all resources
    relaxResources(true);
}
Example 8
Project: Now-Playing-master  File: MusicControlModule.java View source code
@Override
public Map<String, Object> getConstants() {
    Map<String, Object> map = new HashMap<>();
    map.put("STATE_ERROR", PlaybackStateCompat.STATE_ERROR);
    map.put("STATE_STOPPED", PlaybackStateCompat.STATE_STOPPED);
    map.put("STATE_PLAYING", PlaybackStateCompat.STATE_PLAYING);
    map.put("STATE_PAUSED", PlaybackStateCompat.STATE_PAUSED);
    map.put("STATE_BUFFERING", PlaybackStateCompat.STATE_BUFFERING);
    map.put("RATING_HEART", RatingCompat.RATING_HEART);
    map.put("RATING_THUMBS_UP_DOWN", RatingCompat.RATING_THUMB_UP_DOWN);
    map.put("RATING_3_STARS", RatingCompat.RATING_3_STARS);
    map.put("RATING_4_STARS", RatingCompat.RATING_4_STARS);
    map.put("RATING_5_STARS", RatingCompat.RATING_5_STARS);
    map.put("RATING_PERCENTAGE", RatingCompat.RATING_PERCENTAGE);
    return map;
}
Example 9
Project: platform_frameworks_support-master  File: MediaControllerCompat.java View source code
@Override
public void handleMessage(Message msg) {
    if (!mRegistered) {
        return;
    }
    switch(msg.what) {
        case MSG_EVENT:
            onSessionEvent((String) msg.obj, msg.getData());
            break;
        case MSG_UPDATE_PLAYBACK_STATE:
            onPlaybackStateChanged((PlaybackStateCompat) msg.obj);
            break;
        case MSG_UPDATE_METADATA:
            onMetadataChanged((MediaMetadataCompat) msg.obj);
            break;
        case MSG_UPDATE_QUEUE:
            onQueueChanged((List<MediaSessionCompat.QueueItem>) msg.obj);
            break;
        case MSG_UPDATE_QUEUE_TITLE:
            onQueueTitleChanged((CharSequence) msg.obj);
            break;
        case MSG_UPDATE_REPEAT_MODE:
            onRepeatModeChanged((int) msg.obj);
            break;
        case MSG_UPDATE_SHUFFLE_MODE:
            onShuffleModeChanged((boolean) msg.obj);
            break;
        case MSG_UPDATE_EXTRAS:
            onExtrasChanged((Bundle) msg.obj);
            break;
        case MSG_UPDATE_VOLUME:
            onAudioInfoChanged((PlaybackInfo) msg.obj);
            break;
        case MSG_DESTROYED:
            onSessionDestroyed();
            break;
    }
}
Example 10
Project: ponyville-live-android-master  File: PlaybackControlsFragment.java View source code
private void onPlaybackStateChanged(PlaybackStateCompat state) {
    Timber.d(TAG, "onPlaybackStateChanged ", state);
    if (getActivity() == null) {
        Timber.d(TAG, "onPlaybackStateChanged called when getActivity null," + "this should not happen if the callback was properly unregistered. Ignoring.");
        return;
    }
    if (state == null) {
        return;
    }
    boolean enablePlay = false;
    switch(state.getState()) {
        case PlaybackStateCompat.STATE_PAUSED:
        case PlaybackStateCompat.STATE_STOPPED:
            enablePlay = true;
            break;
        case PlaybackStateCompat.STATE_ERROR:
            Timber.d(TAG, "error playbackstate: ", state.getErrorMessage());
            break;
    }
    if (enablePlay) {
        playPause.setImageDrawable(getActivity().getDrawable(R.drawable.ic_play_arrow_black_36dp));
    } else {
        playPause.setImageDrawable(getActivity().getDrawable(R.drawable.ic_pause_black_36dp));
    }
    MediaControllerCompat controller = ((BaseActivity) getActivity()).getMediaControllerCompat();
    String extraInfo = null;
    if (controller != null && controller.getExtras() != null) {
        String castName = controller.getExtras().getString(MusicService.EXTRA_CONNECTED_CAST);
        if (castName != null) {
            extraInfo = getResources().getString(R.string.casting_to_device, castName);
        }
    }
    setExtraInfo(extraInfo);
}
Example 11
Project: sdk-support-master  File: MediaControllerCompat.java View source code
@Override
public void handleMessage(Message msg) {
    if (!mRegistered) {
        return;
    }
    switch(msg.what) {
        case MSG_EVENT:
            onSessionEvent((String) msg.obj, msg.getData());
            break;
        case MSG_UPDATE_PLAYBACK_STATE:
            onPlaybackStateChanged((PlaybackStateCompat) msg.obj);
            break;
        case MSG_UPDATE_METADATA:
            onMetadataChanged((MediaMetadataCompat) msg.obj);
            break;
        case MSG_UPDATE_QUEUE:
            onQueueChanged((List<MediaSessionCompat.QueueItem>) msg.obj);
            break;
        case MSG_UPDATE_QUEUE_TITLE:
            onQueueTitleChanged((CharSequence) msg.obj);
            break;
        case MSG_UPDATE_EXTRAS:
            onExtrasChanged((Bundle) msg.obj);
            break;
        case MSG_UPDATE_VOLUME:
            onAudioInfoChanged((PlaybackInfo) msg.obj);
            break;
        case MSG_DESTROYED:
            onSessionDestroyed();
            break;
    }
}
Example 12
Project: tomahawk-android-master  File: PlaybackService.java View source code
@Override
public void onAudioFocusChange(int focusChange) {
    Log.d(TAG, "onAudioFocusChange. focusChange= " + focusChange);
    if (mIsDestroyed) {
        Log.d(TAG, "onAudioFocusChange. Ignoring because PlaybackService is destroyed");
        return;
    }
    if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        // We have gained focus
        mAudioFocus = AUDIO_FOCUSED;
        if (mPlayState == PlaybackStateCompat.STATE_PAUSED) {
            play(true);
        }
    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        // We have lost focus
        mAudioFocus = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK ? AUDIO_NO_FOCUS_CAN_DUCK : AUDIO_NO_FOCUS_NO_DUCK;
        if (mPlayState == PlaybackStateCompat.STATE_PLAYING) {
            pause(true);
        }
    } else {
        Log.e(TAG, "onAudioFocusChange: Ignoring unsupported focusChange: " + focusChange);
    }
}
Example 13
Project: LyricHere-master  File: MusicService.java View source code
@Override
public void onCreate() {
    super.onCreate();
    LogUtils.d(TAG, "onCreate");
    mPlayingQueue = new ArrayList<>();
    mMusicProvider = new MusicProvider();
    mEventReceiver = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mEventReceiver);
    mMediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);
    // Start a new MediaSession
    mSession = new MediaSessionCompat(this, "MusicService", mEventReceiver, mMediaPendingIntent);
    final MediaSessionCallback cb = new MediaSessionCallback();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Shouldn't really have to do this but the MediaSessionCompat method uses
        // an internal proxy class, which doesn't forward events such as
        // onPlayFromMediaId when running on Lollipop.
        final MediaSession session = (MediaSession) mSession.getMediaSession();
        session.setCallback(new MediaSessionCallbackProxy(cb));
    } else {
        mSession.setCallback(cb);
    }
    setSessionToken(mSession.getSessionToken());
    mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mPlayback = new LocalPlayback(this, mMusicProvider);
    mPlayback.setState(PlaybackStateCompat.STATE_NONE);
    mPlayback.setCallback(this);
    mPlayback.start();
    Context context = getApplicationContext();
    Intent intent = new Intent(context, MusicPlayerActivity.class);
    PendingIntent pi = PendingIntent.getActivity(context, 99, /*request code*/
    intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mSession.setSessionActivity(pi);
    mSessionExtras = new Bundle();
    mSession.setExtras(mSessionExtras);
    updatePlaybackState(null);
    mMediaNotificationManager = new MediaNotificationManager(this);
}
Example 14
Project: News-Android-App-master  File: PodcastNotification.java View source code
@Subscribe
public void onEvent(UpdatePodcastStatusEvent podcast) {
    if (mSession == null)
        return;
    int drawableId = podcast.isPlaying() ? android.R.drawable.ic_media_pause : android.R.drawable.ic_media_play;
    String actionText = podcast.isPlaying() ? "Pause" : "Play";
    if (lastDrawableId != drawableId) {
        lastDrawableId = drawableId;
        createNewNotificationBuilder();
        notificationBuilder.setContentTitle(podcast.getTitle());
        notificationBuilder.addAction(drawableId, actionText, PendingIntent.getBroadcast(mContext, 0, new Intent(mContext, PodcastNotificationToggle.class), PendingIntent.FLAG_ONE_SHOT));
        if (podcast.isPlaying()) {
            //Prevent the Podcast Player from getting killed because of low memory
            //For more info see: http://developer.android.com/reference/android/app/Service.html#startForeground(int, android.app.Notification)
            ((PodcastPlaybackService) mContext).startForeground(NOTIFICATION_ID, notificationBuilder.build());
        } else {
            ((PodcastPlaybackService) mContext).stopForeground(false);
        }
        if (podcast.isPlaying()) {
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_PLAYING, podcast.getCurrent(), 1.0f).setActions(PlaybackStateCompat.ACTION_PAUSE).build());
        } else {
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_PAUSED, podcast.getCurrent(), 0.0f).setActions(PlaybackStateCompat.ACTION_PLAY).build());
        }
    }
    int hours = (int) (podcast.getCurrent() / (1000 * 60 * 60));
    int minutes = (int) (podcast.getCurrent() % (1000 * 60 * 60)) / (1000 * 60);
    int seconds = (int) ((podcast.getCurrent() % (1000 * 60 * 60)) % (1000 * 60) / 1000);
    minutes += hours * 60;
    String fromText = (String.format("%02d:%02d", minutes, seconds));
    hours = (int) (podcast.getMax() / (1000 * 60 * 60));
    minutes = (int) (podcast.getMax() % (1000 * 60 * 60)) / (1000 * 60);
    seconds = (int) ((podcast.getMax() % (1000 * 60 * 60)) % (1000 * 60) / 1000);
    minutes += hours * 60;
    String toText = (String.format("%02d:%02d", minutes, seconds));
    double progressDouble = ((double) podcast.getCurrent() / (double) podcast.getMax()) * 100d;
    int progress = ((int) progressDouble);
    notificationBuilder.setContentText(fromText + " - " + toText).setProgress(100, progress, podcast.getStatus() == PlaybackService.Status.PREPARING);
    notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
Example 15
Project: Noyze-master  File: VolumePanel.java View source code
// All calls will be handles on the main looper (UI Thread).
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
    LOGI("VolumePanel", "handleMessage(" + VolumeMediaReceiver.getMsgName(msg.what) + ')');
    switch(msg.what) {
        // obj: int[3], type, vol, prevVol
        case MSG_VOLUME_CHANGED:
            int[] vals = (int[]) msg.obj;
            // If we just got another event in an unreasonably short period of time,
            // close the system panel and don't handle this event.
            final VolumeChangeInfo lastChangeInfo = mLastVolumeChange;
            mLastVolumeChange = new VolumeChangeInfo(vals[0], vals[1], vals[2]);
            if (null != lastChangeInfo && vals[1] == vals[2]) {
                if ((System.currentTimeMillis() - lastChangeInfo.mEventTime) < 100) {
                    mAudioHelper.closeSystemDialogs(getContext(), VolumePanel.this.getClass().getSimpleName());
                    removeMessages(MSG_VOLUME_CHANGED);
                    return;
                }
            }
            if (mVolumeDirty) {
                onVolumeChanged(vals[0], vals[1], vals[2]);
                mVolumeDirty = false;
            }
            break;
        // arg1: ringer mode
        case MSG_RINGER_MODE_CHANGED:
            mLastRingerMode = mRingerMode;
            mRingerMode = msg.arg1;
            onRingerModeChange(mRingerMode);
            break;
        // arg2: mute mode (boolean 1/0)
        case MSG_MUTE_CHANGED:
            onMuteChanged(msg.arg1, (msg.arg2 == 1));
            break;
        // arg1: speakerphone (0 == off, else on)
        case MSG_SPEAKERPHONE_CHANGED:
            onSpeakerphoneChange(!(msg.arg1 == 0));
            break;
        // arg2: vibrate settings
        case MSG_VIBRATE_MODE_CHANGED:
            onVibrateModeChange(msg.arg1, msg.arg2);
            break;
        // obj: KeyEvent?
        case MSG_MEDIA_BUTTON_EVENT:
            break;
        // obj: KeyEvent
        case MSG_VOLUME_LONG_PRESS:
            KeyEvent event = (KeyEvent) msg.obj;
            if (noLongPress && !hasLongPressAction(event.getKeyCode()))
                return;
            mIgnoreNextKeyUp = true;
            onVolumeLongPress(event);
            break;
        // obj: Pair<Metadata, PlaybackInfo>
        case MSG_PLAY_STATE_CHANGED:
            // Only accept events if the delegate isn't active.
            if (null == mMediaProviderDelegate || !mMediaProviderDelegate.isClientActive()) {
                Pair<MediaMetadataCompat, PlaybackStateCompat> pair = (Pair<MediaMetadataCompat, PlaybackStateCompat>) msg.obj;
                onPlayStateChanged(pair);
            }
            break;
        // arg1: keycode
        case MSG_DISPATCH_KEYEVENT:
            if (Utils.isMediaKeyCode(msg.arg1))
                dispatchMediaKeyEvent(msg.arg1);
            break;
        // arg1: call state
        case MSG_CALL_STATE_CHANGED:
            mCallState = msg.arg1;
            onCallStateChange(mCallState);
            break;
        // obj: audio routes info
        case MSG_AUDIO_ROUTES_CHANGED:
            AudioRoutesInfo info = (AudioRoutesInfo) msg.obj;
            onAudioRoutesChanged(info);
            break;
        case MSG_HEADSET_PLUG:
            int state = msg.arg1;
            onHeadsetPlug(state);
            break;
        case MSG_USER_PRESENT:
            locked = false;
            onLockChange();
            break;
        case MSG_ALARM_CHANGED:
            onAlarmChanged();
            break;
    }
}
Example 16
Project: Playlist-master  File: MediaControlsHelper.java View source code
/**
     * Sets the volatile information for the remote views and controls.  This information is expected to
     * change frequently.
     *
     * @param title The title to display for the notification (e.g. A song name)
     * @param album The name of the album the media is found in
     * @param artist The name of the artist for the media item
     * @param notificationMediaState The current media state for the expanded (big) notification
     */
//getPlaybackOptions() and getPlaybackState() return the correctly annotated items
@SuppressWarnings("ResourceType")
public void update(@Nullable String title, @Nullable String album, @Nullable String artist, @Nullable Bitmap mediaArtwork, @NonNull NotificationHelper.NotificationMediaState notificationMediaState) {
    //Updates the current media MetaData
    MediaMetadataCompat.Builder metaDataBuilder = new MediaMetadataCompat.Builder();
    metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, title);
    metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, album);
    metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, artist);
    if (appIconBitmap != null) {
        metaDataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, appIconBitmap);
    }
    if (mediaArtwork != null) {
        metaDataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, mediaArtwork);
    }
    if (mediaSession != null) {
        mediaSession.setMetadata(metaDataBuilder.build());
    }
    //Updates the available playback controls
    PlaybackStateCompat.Builder playbackStateBuilder = new PlaybackStateCompat.Builder();
    playbackStateBuilder.setActions(getPlaybackOptions(notificationMediaState));
    playbackStateBuilder.setState(getPlaybackState(notificationMediaState.isPlaying()), PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f);
    mediaSession.setPlaybackState(playbackStateBuilder.build());
    Log.d(TAG, "update, controller is null ? " + (mediaSession.getController() == null ? "true" : "false"));
    if (enabled && !mediaSession.isActive()) {
        mediaSession.setActive(true);
    }
}
Example 17
Project: torrenttunes-android-master  File: MusicService.java View source code
/*
     * (non-Javadoc)
     * @see android.app.Service#onCreate()
     */
@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");
    mPlayingQueue = new ArrayList<>();
    mMusicProvider = new MusicProvider();
    mPackageValidator = new PackageValidator(this);
    mEventReceiver = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mEventReceiver);
    mMediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);
    // Start a new MediaSession
    mSession = new MediaSessionCompat(this, "MusicService", mEventReceiver, mMediaPendingIntent);
    final MediaSessionCallback cb = new MediaSessionCallback();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Shouldn't really have to do this but the MediaSessionCompat method uses
        // an internal proxy class, which doesn't forward events such as
        // onPlayFromMediaId when running on Lollipop.
        final MediaSession session = (MediaSession) mSession.getMediaSession();
    // session.setCallback(new MediaSessionCallbackProxy(cb));
    } else {
        mSession.setCallback(cb);
    }
    setSessionToken(mSession.getSessionToken());
    mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mPlayback = new LocalPlayback(this, mMusicProvider);
    mPlayback.setState(PlaybackStateCompat.STATE_NONE);
    mPlayback.setCallback(this);
    mPlayback.start();
    Context context = getApplicationContext();
    Intent intent = new Intent(context, NowPlayingActivity.class);
    PendingIntent pi = PendingIntent.getActivity(context, 99, /*request code*/
    intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mSession.setSessionActivity(pi);
    mSessionExtras = new Bundle();
    CarHelper.setSlotReservationFlags(mSessionExtras, true, true, true);
    mSession.setExtras(mSessionExtras);
    updatePlaybackState(null);
    mMediaNotificationManager = new MediaNotificationManager(this);
    mCastManager = VideoCastManager.getInstance();
    mCastManager.addVideoCastConsumer(mCastConsumer);
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
}
Example 18
Project: VoiceControlForPlex-master  File: VoiceControlForPlexApplication.java View source code
public void setNotification(final PlexClient client, final PlayerState currentState, final PlexMedia media, final ArrayList<? extends PlexMedia> playlist, final MediaSessionCompat mediaSession) {
    if (client == null) {
        logger.d("Client is null for some reason");
        return;
    }
    if (client.isLocalDevice())
        return;
    final int[] numBitmapsFetched = new int[] { 0 };
    final int[] numBitmapsToFetch = new int[] { 0 };
    // Figure out which track in the playlist this is, to know whether or not to set up the Intent to handle previous/next
    final int[] playlistIndexF = new int[1];
    for (int i = 0; i < playlist.size(); i++) {
        //      logger.d("comparing %s to %s (%s)", playlist.get(i).key, media.key, playlist.get(i).key.equals(media.key));
        if (playlist.get(i).equals(media)) {
            //        logger.d("found a match for %s", media.key);
            playlistIndexF[0] = i;
            break;
        }
    }
    final int playlistIndex = playlistIndexF[0];
    PlexMedia.IMAGE_KEY keyIcon = media instanceof PlexTrack ? PlexMedia.IMAGE_KEY.NOTIFICATION_THUMB_MUSIC_BIG : PlexMedia.IMAGE_KEY.NOTIFICATION_THUMB_BIG;
    PlexMedia.IMAGE_KEY keyBackground = media instanceof PlexTrack ? PlexMedia.IMAGE_KEY.NOTIFICATION_MUSIC_BACKGROUND : PlexMedia.IMAGE_KEY.NOTIFICATION_BACKGROUND;
    final Bitmap[] bitmapsFetched = new Bitmap[2];
    final Runnable onFinished = () -> {
        // this is where the magic happens!
        android.content.Intent playIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
        playIntent.setAction(Intent.ACTION_PLAY);
        playIntent.putExtra(SubscriptionService.CLIENT, client);
        playIntent.putExtra(SubscriptionService.MEDIA, media);
        playIntent.putParcelableArrayListExtra(Intent.EXTRA_PLAYLIST, playlist);
        PendingIntent playPendingIntent = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, playIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        android.content.Intent pauseIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
        pauseIntent.setAction(Intent.ACTION_PAUSE);
        pauseIntent.putExtra(SubscriptionService.CLIENT, client);
        pauseIntent.putExtra(SubscriptionService.MEDIA, media);
        pauseIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
        PendingIntent pausePendingIntent = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        android.content.Intent disconnectIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
        disconnectIntent.setAction(Intent.ACTION_DISCONNECT);
        disconnectIntent.putExtra(SubscriptionService.CLIENT, client);
        disconnectIntent.putExtra(SubscriptionService.MEDIA, media);
        disconnectIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
        PendingIntent piDisconnect = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, disconnectIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        android.content.Intent nowPlayingIntent = new android.content.Intent(VoiceControlForPlexApplication.this, MainActivity.class);
        nowPlayingIntent.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK | android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK);
        nowPlayingIntent.setAction(MainActivity.ACTION_SHOW_NOW_PLAYING);
        nowPlayingIntent.putExtra(Intent.EXTRA_MEDIA, media);
        nowPlayingIntent.putExtra(Intent.EXTRA_CLIENT, client);
        nowPlayingIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
        PendingIntent piNowPlaying = PendingIntent.getActivity(VoiceControlForPlexApplication.this, 0, nowPlayingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        android.content.Intent rewindIntent;
        android.content.Intent forwardIntent;
        android.content.Intent previousIntent;
        android.content.Intent nextIntent;
        List<NotificationCompat.Action> actions = new ArrayList<>();
        if (!media.isMusic()) {
            rewindIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
            rewindIntent.setAction(Intent.ACTION_REWIND);
            rewindIntent.putExtra(SubscriptionService.CLIENT, client);
            rewindIntent.putExtra(SubscriptionService.MEDIA, media);
            rewindIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
            PendingIntent piRewind = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, rewindIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            forwardIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
            forwardIntent.setAction(Intent.ACTION_FORWARD);
            forwardIntent.putExtra(SubscriptionService.CLIENT, client);
            forwardIntent.putExtra(SubscriptionService.MEDIA, media);
            forwardIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
            PendingIntent piForward = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, forwardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_rewind, "Rewind", piRewind).build());
            if (currentState == PlayerState.PAUSED)
                actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_play, "Play", playPendingIntent).build());
            else
                actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_pause, "Pause", pausePendingIntent).build());
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_forward, "Fast Forward", piForward).build());
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_disconnect, "Disconnect", piDisconnect).build());
        } else {
            PendingIntent piPrevious = null;
            if (playlistIndex > 0) {
                previousIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
                previousIntent.setAction(Intent.ACTION_PREVIOUS);
                previousIntent.putExtra(SubscriptionService.CLIENT, client);
                previousIntent.putExtra(SubscriptionService.MEDIA, media);
                previousIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
                piPrevious = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, previousIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            }
            PendingIntent piNext = null;
            if (playlistIndex + 1 < playlist.size()) {
                nextIntent = new android.content.Intent(VoiceControlForPlexApplication.this, client.isLocalClient ? LocalMusicService.class : SubscriptionService.class);
                nextIntent.setAction(Intent.ACTION_NEXT);
                nextIntent.putExtra(SubscriptionService.CLIENT, client);
                nextIntent.putExtra(SubscriptionService.MEDIA, media);
                nextIntent.putExtra(Intent.EXTRA_PLAYLIST, playlist);
                piNext = PendingIntent.getService(VoiceControlForPlexApplication.this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            }
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_previous, "Previous", piPrevious).build());
            if (currentState == PlayerState.PAUSED)
                actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_play, "Play", playPendingIntent).build());
            else
                actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_pause, "Pause", pausePendingIntent).build());
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_next, "Next", piNext).build());
            actions.add(new NotificationCompat.Action.Builder(R.drawable.notif_disconnect, "Disconnect", piDisconnect).build());
        }
        Notification n;
        NotificationCompat.Builder builder = new NotificationCompat.Builder(VoiceControlForPlexApplication.this);
        // Show controls on lock screen even when user hides sensitive content.
        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setSmallIcon(R.drawable.vcfp_notification).setAutoCancel(false).setOngoing(true).setOnlyAlertOnce(true).setDefaults(Notification.DEFAULT_ALL).setStyle(// Apply the media style template
        new NotificationCompat.MediaStyle().setShowActionsInCompactView(0, 1, 2).setMediaSession(mediaSession.getSessionToken())).setContentTitle(media.getNotificationTitle()).setContentText(media.getNotificationSubtitle()).setContentIntent(piNowPlaying).setLargeIcon(bitmapsFetched[0]);
        for (NotificationCompat.Action action : actions) {
            builder.addAction(action);
        }
        n = builder.build();
        try {
            // Disable notification sound
            n.defaults = 0;
            mNotifyMgr.notify(nowPlayingNotificationId, n);
            Logger.d("Notification set");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        mediaSession.setMetadata(new MediaMetadataCompat.Builder().putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bitmapsFetched[1]).putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, media.art).putString(MediaMetadataCompat.METADATA_KEY_ARTIST, media.getNotificationTitle()).build());
        mediaSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(currentState == PlayerState.PAUSED ? PlaybackStateCompat.STATE_PAUSED : PlaybackStateCompat.STATE_PLAYING, Long.parseLong(media.viewOffset), 1f).build());
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    };
    // Check if the bitmaps have already been fetched. If they have, launch the runnable to set the notification
    Bitmap bitmap = getCachedBitmap(media.getImageKey(keyIcon));
    Bitmap bigBitmap = getCachedBitmap(media.getImageKey(keyBackground));
    if (bitmap != null && bigBitmap != null) {
        bitmapsFetched[0] = bitmap;
        bitmapsFetched[1] = bigBitmap;
        onFinished.run();
    } else {
        ArrayList<FetchMediaImageTask> taskList = new ArrayList<>();
        if (media.getNotificationThumb(keyIcon) != null) {
            numBitmapsToFetch[0]++;
            // Fetch both (big and regular) versions of the notification bitmap, and when both are finished, launch the runnable above that will set the notification
            taskList.add(new FetchMediaImageTask(media, PlexMedia.IMAGE_SIZES.get(keyIcon)[0], PlexMedia.IMAGE_SIZES.get(keyIcon)[1], media.getNotificationThumb(keyIcon), media.getImageKey(keyIcon), new BitmapHandler() {

                @Override
                public void onSuccess(Bitmap bitmap) {
                    bitmapsFetched[0] = bitmap;
                    if (numBitmapsFetched[0] + 1 == numBitmapsToFetch[0])
                        onFinished.run();
                    numBitmapsFetched[0]++;
                }
            }));
        }
        if (media.getNotificationThumb(keyBackground) != null) {
            numBitmapsToFetch[0]++;
            taskList.add(new FetchMediaImageTask(media, PlexMedia.IMAGE_SIZES.get(keyBackground)[0], PlexMedia.IMAGE_SIZES.get(keyBackground)[1], media.getNotificationThumb(keyBackground), media.getImageKey(keyBackground), new BitmapHandler() {

                @Override
                public void onSuccess(Bitmap bitmap) {
                    bitmapsFetched[1] = bitmap;
                    if (numBitmapsFetched[0] + 1 == numBitmapsToFetch[0])
                        onFinished.run();
                    numBitmapsFetched[0]++;
                }
            }));
        }
        if (taskList.size() == 0)
            onFinished.run();
        else
            for (FetchMediaImageTask task : taskList) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}
Example 19
Project: Easy-Notification-master  File: EasyNotificationFragment.java View source code
@Override
public void onPlaybackStateChanged(int state) {
    switch(state) {
        case PlaybackStateCompat.STATE_PLAYING:
            mHandler.removeMessages(MSG_HIDE_MEDIA_WIDGET);
            makeMediaWidgetActive();
            break;
        default:
            if (mMediaWidgetActive) {
                // 6 sec.
                int delay = 6000;
                if (state == PlaybackStateCompat.STATE_NONE)
                    delay = 500;
                mHandler.sendEmptyMessageDelayed(MSG_HIDE_MEDIA_WIDGET, delay);
            }
            break;
    }
}
Example 20
Project: odyssey-master  File: PlaybackServiceStatusHelper.java View source code
/**
     * Stops the android mediasession.
     */
public void stopMediaSession() {
    // Make sure to remove the old metadata.
    mMediaSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_STOPPED, 0, 0.0f).build());
    // Clear last track so that covers load again when resuming.
    mLastTrack = null;
    // Actual session disable.
    mMediaSession.setActive(false);
}
Example 21
Project: AndroidChromium-master  File: MediaNotificationManager.java View source code
private void updateMediaSession() {
    if (!mMediaNotificationInfo.supportsPlayPause())
        return;
    if (mMediaSession == null)
        mMediaSession = createMediaSession();
    try {
        // Tell the MediaRouter about the session, so that Chrome can control the volume
        // on the remote cast device (if any).
        // Pre-MR1 versions of JB do not have the complete MediaRouter APIs,
        // so getting the MediaRouter instance will throw an exception.
        MediaRouter.getInstance(mContext).setMediaSessionCompat(mMediaSession);
    } catch (NoSuchMethodError e) {
    }
    mMediaSession.setMetadata(createMetadata());
    PlaybackStateCompat.Builder playbackStateBuilder = new PlaybackStateCompat.Builder().setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE);
    if (mMediaNotificationInfo.isPaused) {
        playbackStateBuilder.setState(PlaybackStateCompat.STATE_PAUSED, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f);
    } else {
        // If notification only supports stop, still pretend
        playbackStateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f);
    }
    mMediaSession.setPlaybackState(playbackStateBuilder.build());
}
Example 22
Project: android-support-v4-master  File: MediaControllerCompat.java View source code
@Override
public void handleMessage(Message msg) {
    if (!mRegistered) {
        return;
    }
    switch(msg.what) {
        case MSG_EVENT:
            onSessionEvent((String) msg.obj, msg.getData());
            break;
        case MSG_UPDATE_PLAYBACK_STATE:
            onPlaybackStateChanged((PlaybackStateCompat) msg.obj);
            break;
        case MSG_UPDATE_METADATA:
            onMetadataChanged((MediaMetadataCompat) msg.obj);
            break;
        case MSG_UPDATE_QUEUE:
            onQueueChanged((List<MediaSessionCompat.QueueItem>) msg.obj);
            break;
        case MSG_UPDATE_QUEUE_TITLE:
            onQueueTitleChanged((CharSequence) msg.obj);
            break;
        case MSG_UPDATE_EXTRAS:
            onExtrasChanged((Bundle) msg.obj);
            break;
        case MSG_UPDATE_VOLUME:
            onAudioInfoChanged((PlaybackInfo) msg.obj);
            break;
        case MSG_DESTROYED:
            onSessionDestroyed();
            break;
    }
}
Example 23
Project: Jockey-master  File: MusicPlayer.java View source code
/**
     * Initiate a MediaSession to allow the Android system to interact with the player
     */
private void initMediaSession() {
    Timber.i("Initializing MediaSession");
    MediaSessionCompat session = new MediaSessionCompat(mContext, TAG, null, null);
    session.setCallback(new MediaSessionCallback(this));
    session.setSessionActivity(PendingIntent.getActivity(mContext, 0, MainActivity.newNowPlayingIntent(mContext).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_CANCEL_CURRENT));
    session.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    PlaybackStateCompat.Builder state = new PlaybackStateCompat.Builder().setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS | PlaybackStateCompat.ACTION_STOP).setState(PlaybackStateCompat.STATE_NONE, 0, 0f);
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setClass(mContext, MediaButtonReceiver.class);
    PendingIntent mbrIntent = PendingIntent.getBroadcast(mContext, 0, mediaButtonIntent, 0);
    session.setMediaButtonReceiver(mbrIntent);
    session.setPlaybackState(state.build());
    session.setActive(true);
    mMediaSession = session;
}
Example 24
Project: quran_android-master  File: AudioService.java View source code
private void updateAudioPlayPosition() {
    Timber.d("updateAudioPlayPosition");
    if (mAudioRequest == null) {
        return;
    }
    if (mPlayer != null || mGaplessSuraData == null) {
        int sura = mAudioRequest.getCurrentSura();
        int ayah = mAudioRequest.getCurrentAyah();
        int updatedAyah = ayah;
        int maxAyahs = QuranInfo.getNumAyahs(sura);
        if (sura != mGaplessSura) {
            return;
        }
        setState(PlaybackStateCompat.STATE_PLAYING);
        int pos = mPlayer.getCurrentPosition();
        Integer ayahTime = mGaplessSuraData.get(ayah);
        Timber.d("updateAudioPlayPosition: %d:%d, currently at %d vs expected at %d", sura, ayah, pos, ayahTime);
        if (ayahTime > pos) {
            int iterAyah = ayah;
            while (--iterAyah > 0) {
                ayahTime = mGaplessSuraData.get(iterAyah);
                if (ayahTime <= pos) {
                    updatedAyah = iterAyah;
                    break;
                } else {
                    updatedAyah--;
                }
            }
        } else {
            int iterAyah = ayah;
            while (++iterAyah <= maxAyahs) {
                ayahTime = mGaplessSuraData.get(iterAyah);
                if (ayahTime > pos) {
                    updatedAyah = iterAyah - 1;
                    break;
                } else {
                    updatedAyah++;
                }
            }
        }
        Timber.d("updateAudioPlayPosition: %d:%d, decided ayah should be: %d", sura, ayah, updatedAyah);
        if (updatedAyah != ayah) {
            ayahTime = mGaplessSuraData.get(ayah);
            if (Math.abs(pos - ayahTime) < 150) {
                // shouldn't change ayahs if the delta is just 150ms...
                mHandler.sendEmptyMessageDelayed(MSG_UPDATE_AUDIO_POS, 150);
                return;
            }
            SuraAyah nextAyah = mAudioRequest.setCurrentAyah(sura, updatedAyah);
            if (nextAyah == null) {
                processStopRequest();
                return;
            } else if (nextAyah.sura != sura || nextAyah.ayah != updatedAyah) {
                // remove any messages currently in the queue
                mHandler.removeCallbacksAndMessages(null);
                // if the ayah hasn't changed, we're repeating the ayah,
                // otherwise, we're repeating a range. this variable is
                // what determines whether or not we replay the basmallah.
                final boolean ayahRepeat = (ayah == nextAyah.ayah && sura == nextAyah.sura);
                if (ayahRepeat) {
                    // jump back to the ayah we should repeat and play it
                    pos = getSeekPosition(true);
                    mPlayer.seekTo(pos);
                } else {
                    // we're repeating into a different sura
                    final boolean flag = sura != mAudioRequest.getCurrentSura();
                    playAudio(flag);
                }
                return;
            }
            // moved on to next ayah
            updateNotification();
        } else {
            // if we have end of sura info and we bypassed end of sura
            // line, switch the sura.
            ayahTime = mGaplessSuraData.get(999);
            if (ayahTime > 0 && pos >= ayahTime) {
                SuraAyah repeat = mAudioRequest.setCurrentAyah(sura + 1, 1);
                if (repeat != null && repeat.sura == sura) {
                    // remove any messages currently in the queue
                    mHandler.removeCallbacksAndMessages(null);
                    // jump back to the ayah we should repeat and play it
                    pos = getSeekPosition(false);
                    mPlayer.seekTo(pos);
                } else {
                    playAudio(true);
                }
                return;
            }
        }
        notifyAyahChanged();
        if (maxAyahs >= (updatedAyah + 1)) {
            Integer t = mGaplessSuraData.get(updatedAyah + 1);
            t = t - mPlayer.getCurrentPosition();
            Timber.d("updateAudioPlayPosition postingDelayed after: %d", t);
            if (t < 100) {
                t = 100;
            } else if (t > 10000) {
                t = 10000;
            }
            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_AUDIO_POS, t);
        }
    // if we're on the last ayah, don't do anything - let the file
    // complete on its own to avoid getCurrentPosition() bugs.
    }
}
Example 25
Project: AntennaPod-master  File: PlaybackService.java View source code
/**
     * Updates the Media Session for the corresponding status.
     * @param playerStatus the current {@link PlayerStatus}
     */
private void updateMediaSession(final PlayerStatus playerStatus) {
    PlaybackStateCompat.Builder sessionState = new PlaybackStateCompat.Builder();
    int state;
    if (playerStatus != null) {
        switch(playerStatus) {
            case PLAYING:
                state = PlaybackStateCompat.STATE_PLAYING;
                break;
            case PREPARED:
            case PAUSED:
                state = PlaybackStateCompat.STATE_PAUSED;
                break;
            case STOPPED:
                state = PlaybackStateCompat.STATE_STOPPED;
                break;
            case SEEKING:
                state = PlaybackStateCompat.STATE_FAST_FORWARDING;
                break;
            case PREPARING:
            case INITIALIZING:
                state = PlaybackStateCompat.STATE_CONNECTING;
                break;
            case INITIALIZED:
            case INDETERMINATE:
                state = PlaybackStateCompat.STATE_NONE;
                break;
            case ERROR:
                state = PlaybackStateCompat.STATE_ERROR;
                break;
            default:
                state = PlaybackStateCompat.STATE_NONE;
                break;
        }
    } else {
        state = PlaybackStateCompat.STATE_NONE;
    }
    sessionState.setState(state, mediaPlayer.getPosition(), mediaPlayer.getPlaybackSpeed());
    sessionState.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_REWIND | PlaybackStateCompat.ACTION_FAST_FORWARD | PlaybackStateCompat.ACTION_SKIP_TO_NEXT);
    mediaSession.setPlaybackState(sessionState.build());
}
Example 26
Project: TiM-master  File: MusicService.java View source code
private void updateMediaSession(final String what) {
    int playState = mIsSupposedToBePlaying ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
    if (what.equals(PLAYSTATE_CHANGED) || what.equals(POSITION_CHANGED)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f).setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS).build());
        }
    } else if (what.equals(META_CHANGED) || what.equals(QUEUE_CHANGED)) {
        Bitmap albumArt = ImageLoader.getInstance().loadImageSync(TimberUtils.getAlbumArtUri(getAlbumId()).toString());
        if (albumArt != null) {
            Bitmap.Config config = albumArt.getConfig();
            if (config == null) {
                config = Bitmap.Config.ARGB_8888;
            }
            albumArt = albumArt.copy(config, false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setMetadata(new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_ARTIST, getArtistName()).putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, getAlbumArtistName()).putString(MediaMetadataCompat.METADATA_KEY_ALBUM, getAlbumName()).putString(MediaMetadataCompat.METADATA_KEY_TITLE, getTrackName()).putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration()).putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, getQueuePosition() + 1).putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, getQueue().length).putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName()).putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, mShowAlbumArtOnLockscreen ? albumArt : null).build());
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f).setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS).build());
        }
    }
}
Example 27
Project: Timber-master  File: MusicService.java View source code
private void updateMediaSession(final String what) {
    int playState = mIsSupposedToBePlaying ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
    if (what.equals(PLAYSTATE_CHANGED) || what.equals(POSITION_CHANGED)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f).setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS).build());
        }
    } else if (what.equals(META_CHANGED) || what.equals(QUEUE_CHANGED)) {
        Bitmap albumArt = ImageLoader.getInstance().loadImageSync(TimberUtils.getAlbumArtUri(getAlbumId()).toString());
        if (albumArt != null) {
            Bitmap.Config config = albumArt.getConfig();
            if (config == null) {
                config = Bitmap.Config.ARGB_8888;
            }
            albumArt = albumArt.copy(config, false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setMetadata(new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_ARTIST, getArtistName()).putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, getAlbumArtistName()).putString(MediaMetadataCompat.METADATA_KEY_ALBUM, getAlbumName()).putString(MediaMetadataCompat.METADATA_KEY_TITLE, getTrackName()).putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration()).putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, getQueuePosition() + 1).putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, getQueue().length).putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName()).putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, mShowAlbumArtOnLockscreen ? albumArt : null).build());
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f).setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS).build());
        }
    }
}
Example 28
Project: VCL-Android-master  File: PlaybackService.java View source code
protected void publishState(int state) {
    if (mMediaSession == null)
        return;
    PlaybackStateCompat.Builder bob = new PlaybackStateCompat.Builder();
    bob.setActions(PLAYBACK_ACTIONS);
    switch(state) {
        case MediaPlayer.Event.Playing:
            bob.setState(PlaybackStateCompat.STATE_PLAYING, -1, 1);
            break;
        case MediaPlayer.Event.Stopped:
            bob.setState(PlaybackStateCompat.STATE_STOPPED, -1, 0);
            break;
        default:
            bob.setState(PlaybackStateCompat.STATE_PAUSED, -1, 0);
    }
    PlaybackStateCompat pbState = bob.build();
    mMediaSession.setPlaybackState(pbState);
    mMediaSession.setActive(state != PlaybackStateCompat.STATE_STOPPED);
}
Example 29
Project: CastCompanionLibrary-android-master  File: VideoCastManager.java View source code
/*
     * Sets up the {@link MediaSessionCompat} for this application. It also handles the audio
     * focus.
     */
@SuppressLint("InlinedApi")
private void setUpMediaSession(final MediaInfo info) {
    if (!isFeatureEnabled(CastConfiguration.FEATURE_LOCKSCREEN)) {
        return;
    }
    if (mMediaSessionCompat == null) {
        ComponentName mediaEventReceiver = new ComponentName(mContext, VideoIntentReceiver.class.getName());
        mMediaSessionCompat = new MediaSessionCompat(mContext, "TAG", mediaEventReceiver, null);
        mMediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mMediaSessionCompat.setActive(true);
        mMediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {

            @Override
            public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
                KeyEvent keyEvent = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
                if (keyEvent != null && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PAUSE || keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY)) {
                    toggle();
                }
                return true;
            }

            @Override
            public void onPlay() {
                toggle();
            }

            @Override
            public void onPause() {
                toggle();
            }

            private void toggle() {
                try {
                    togglePlayback();
                } catch (CastExceptionTransientNetworkDisconnectionException | NoConnectionException |  e) {
                    LOGE(TAG, "MediaSessionCompat.Callback(): Failed to toggle playback", e);
                }
            }
        });
    }
    mAudioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
    PendingIntent pi = getCastControllerPendingIntent();
    if (pi != null) {
        mMediaSessionCompat.setSessionActivity(pi);
    }
    if (info == null) {
        mMediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_NONE, 0, 1.0f).build());
    } else {
        mMediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_PLAYING, 0, 1.0f).setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());
    }
    // Update the media session's image
    updateLockScreenImage(info);
    // update the media session's metadata
    updateMediaSessionMetadata();
    mMediaRouter.setMediaSessionCompat(mMediaSessionCompat);
}
Example 30
Project: ListenerMusicPlayer-master  File: MusicService.java View source code
/**
     * æ›´æ–°PlaybackStateCompat
     * @param what
     */
private void updateMediaSession(final String what) {
    int playState = mIsSupposedToBePlaying ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
    if (what.equals(PLAYSTATE_CHANGED) || what.equals(POSITION_CHANGED)) {
        //播放状�改�时
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f).setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS).build());
        }
    } else if (what.equals(META_CHANGED) || what.equals(QUEUE_CHANGED)) {
        //当�播放歌曲的信�或者播放队列改�
        Bitmap albumArt = ImageLoader.getInstance().loadImageSync(ListenerUtil.getAlbumArtUri(getAlbumId()).toString());
        if (albumArt != null) {
            Bitmap.Config config = albumArt.getConfig();
            if (config == null) {
                config = Bitmap.Config.ARGB_8888;
            }
            albumArt = albumArt.copy(config, false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setMetadata(new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_ARTIST, getArtistName()).putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, getAlbumArtistName()).putString(MediaMetadataCompat.METADATA_KEY_ALBUM, getAlbumName()).putString(MediaMetadataCompat.METADATA_KEY_TITLE, getTrackName()).putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration()).putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, getQueuePosition() + 1).putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, getQueue().length).putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName()).putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, mShowAlbumArtOnLockscreen ? albumArt : null).build());
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f).setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS).build());
        }
    }
}
Example 31
Project: shuttle-master  File: VideoCastManager.java View source code
/*
     * Sets up the {@link MediaSessionCompat} for this application. It also handles the audio
     * focus.
     */
@SuppressLint("InlinedApi")
private void setUpMediaSession(final MediaInfo info) {
    if (!isFeatureEnabled(CastConfiguration.FEATURE_LOCKSCREEN)) {
        return;
    }
    if (mMediaSessionCompat == null) {
        ComponentName mediaEventReceiver = new ComponentName(mContext, VideoIntentReceiver.class.getName());
        mMediaSessionCompat = new MediaSessionCompat(mContext, "TAG", mediaEventReceiver, null);
        mMediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mMediaSessionCompat.setActive(true);
        mMediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {

            @Override
            public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
                KeyEvent keyEvent = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
                if (keyEvent != null && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PAUSE || keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY)) {
                    toggle();
                }
                return true;
            }

            @Override
            public void onPlay() {
                toggle();
            }

            @Override
            public void onPause() {
                toggle();
            }

            private void toggle() {
                try {
                    togglePlayback();
                } catch (CastExceptionTransientNetworkDisconnectionException | NoConnectionException |  e) {
                    LOGE(TAG, "MediaSessionCompat.Callback(): Failed to toggle playback", e);
                }
            }
        });
    }
    mAudioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
    PendingIntent pi = getCastControllerPendingIntent();
    if (pi != null) {
        mMediaSessionCompat.setSessionActivity(pi);
    }
    if (info == null) {
        mMediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_NONE, 0, 1.0f).build());
    } else {
        mMediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_PLAYING, 0, 1.0f).setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());
    }
    // Update the media session's image
    updateLockScreenImage(info);
    // update the media session's metadata
    updateMediaSessionMetadata();
    mMediaRouter.setMediaSessionCompat(mMediaSessionCompat);
}
Example 32
Project: androidtv-Leanback-master  File: PlaybackOverlayFragment.java View source code
private void setPlaybackState(int state) {
    long currPosition = getCurrentPosition();
    PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder().setActions(getAvailableActions(state));
    stateBuilder.setState(state, currPosition, 1.0f);
    mSession.setPlaybackState(stateBuilder.build());
}
Example 33
Project: Phonograph-master  File: MusicService.java View source code
private void updateMediaSessionPlaybackState() {
    mediaSession.setPlaybackState(new PlaybackStateCompat.Builder().setActions(MEDIA_SESSION_ACTIONS).setState(isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED, getPosition(), 1).build());
}