Example usage for android.support.v4.media.session MediaSessionCompat MediaSessionCompat

List of usage examples for android.support.v4.media.session MediaSessionCompat MediaSessionCompat

Introduction

In this page you can find the example usage for android.support.v4.media.session MediaSessionCompat MediaSessionCompat.

Prototype

public MediaSessionCompat(@NonNull Context context, @NonNull String tag, @Nullable ComponentName mbrComponent,
        @Nullable PendingIntent mbrIntent) 

Source Link

Document

Creates a new session with a specified media button receiver (a component name and/or a pending intent).

Usage

From source file:com.baruckis.nanodegree.spotifystreamer.PlayerService.java

private void initMediaSession() {

    mSession = new MediaSessionCompat(getApplicationContext(), "media_player_session", null, null);

    try {/*w  w  w  .  j a va 2  s . c om*/
        mController = new MediaControllerCompat(getApplicationContext(), mSession.getSessionToken());
    } catch (RemoteException e) {
        e.printStackTrace();
    }

    mSession.setCallback(new MediaSessionCompat.Callback() {
        @Override
        public void onPlay() {
            if (mListener != null) {
                mListener.onPlayTrack();
            }
        }

        @Override
        public void onPause() {
            if (!mIsError && mListener != null) {
                mListener.onPauseTrack();
            }
            if (mIsError) {
                isPlaybackPausedByUser = true;
                buildNotification(generateAction(android.R.drawable.ic_media_play, "Play", ACTION_PLAY), false);
                if (mListener != null) {
                    mListener.onError();
                }
            }
        }

        @Override
        public void onSkipToNext() {
            if (mListener != null) {
                mListener.onNextTrack();
            }
        }

        @Override
        public void onSkipToPrevious() {
            if (mListener != null) {
                mListener.onPreviousTrack();
            }
        }
    });
}

From source file:com.torrenttunes.android.MusicService.java

@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 {//w w w .j  av a  2  s  .co m
        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());
}

From source file:org.chromium.chrome.browser.media.ui.NotificationMediaPlaybackControls.java

private void updateNotification() {
    if (mService == null)
        return;//from w ww.jav a2  s .  c  om

    if (mMediaNotificationInfo == null) {
        // Notification was hidden before we could update it.
        assert mNotificationBuilder == null;
        return;
    }

    // Android doesn't badge the icons for RemoteViews automatically when
    // running the app under the Work profile.
    if (mNotificationIcon == null) {
        Drawable notificationIconDrawable = ApiCompatibilityUtils.getUserBadgedIcon(mContext,
                R.drawable.audio_playing);
        mNotificationIcon = drawableToBitmap(notificationIconDrawable);
    }

    if (mNotificationBuilder == null) {
        mNotificationBuilder = new NotificationCompat.Builder(mContext).setSmallIcon(R.drawable.audio_playing)
                .setAutoCancel(false).setLocalOnly(true)
                .setDeleteIntent(mService.getPendingIntent(ListenerService.ACTION_STOP));
    }
    mNotificationBuilder.setOngoing(!mMediaNotificationInfo.isPaused);
    mNotificationBuilder.setContentIntent(createContentIntent());

    RemoteViews contentView = createContentView();

    contentView.setTextViewText(R.id.title, mMediaNotificationInfo.title);
    contentView.setTextViewText(R.id.status, getStatus());
    if (mNotificationIcon != null) {
        contentView.setImageViewBitmap(R.id.icon, mNotificationIcon);
    } else {
        contentView.setImageViewResource(R.id.icon, R.drawable.audio_playing);
    }

    if (mMediaNotificationInfo.isPaused) {
        contentView.setImageViewResource(R.id.playpause, R.drawable.ic_vidcontrol_play);
        contentView.setContentDescription(R.id.playpause, mPlayDescription);
        contentView.setOnClickPendingIntent(R.id.playpause,
                mService.getPendingIntent(ListenerService.ACTION_PLAY));
    } else {
        contentView.setImageViewResource(R.id.playpause, R.drawable.ic_vidcontrol_pause);
        contentView.setContentDescription(R.id.playpause, mPauseDescription);
        contentView.setOnClickPendingIntent(R.id.playpause,
                mService.getPendingIntent(ListenerService.ACTION_PAUSE));
    }

    mNotificationBuilder.setContent(contentView);
    mNotificationBuilder.setVisibility(mMediaNotificationInfo.isPrivate ? NotificationCompat.VISIBILITY_PRIVATE
            : NotificationCompat.VISIBILITY_PUBLIC);

    if (mMediaSession == null) {
        mMediaSession = new MediaSessionCompat(mContext, mContext.getString(R.string.app_name),
                new ComponentName(mContext.getPackageName(), MediaButtonReceiver.class.getName()), null);
        mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
                | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mMediaSession.setCallback(mMediaSessionCallback);
        mMediaSession.setActive(true);
    }

    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 {
        playbackStateBuilder.setState(PlaybackStateCompat.STATE_PLAYING,
                PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f);
    }
    mMediaSession.setPlaybackState(playbackStateBuilder.build());

    Notification notification = mNotificationBuilder.build();

    // We keep the service as a foreground service while the media is playing. When it is not,
    // the service isn't stopped but is no longer in foreground, thus at a lower priority.
    // While the service is in foreground, the associated notification can't be swipped away.
    // Moving it back to background allows the user to remove the notification.
    if (mMediaNotificationInfo.isPaused) {
        mService.stopForeground(false /* removeNotification */);

        NotificationManagerCompat manager = NotificationManagerCompat.from(mContext);
        manager.notify(R.id.media_playback_notification, notification);
    } else {
        mService.startForeground(R.id.media_playback_notification, notification);
    }
}

From source file:com.massivcode.androidmusicplayer.services.MusicService.java

private void setMetaData() {
    if (mCurrentMusicInfo != null) {
        Bitmap bitmap = MusicInfoLoadUtil.getBitmap(getApplicationContext(), mCurrentMusicInfo.getUri(), 4);
        mMetadata = new MediaMetadataCompat.Builder()
                .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bitmap)
                .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, mCurrentMusicInfo.getArtist())
                .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, mCurrentMusicInfo.getAlbum())
                .putString(MediaMetadataCompat.METADATA_KEY_TITLE, mCurrentMusicInfo.getTitle()).build();
        if (mSession == null) {
            mSession = new MediaSessionCompat(this, "tag", null, null);
            mSession.setMetadata(mMetadata);
            mSession.setActive(true);//  ww w.  j  a v a  2  s .  c  o  m
            mSession.setCallback(new MediaSessionCompat.Callback() {
                @Override
                public void onPlay() {
                    super.onPlay();
                    Toast.makeText(MusicService.this, "onPlay", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

From source file:singh.amandeep.musicplayer.MusicService.java

private void setUpMediaSession() {
    mSession = new MediaSessionCompat(this, "Music Player", mMediaButtonReceiverComponent, mShutdownIntent);
    mSession.setCallback(new MediaSessionCompat.Callback() {
        @Override/* w  w  w  .  j av a2s .  co  m*/
        public void onPause() {
            pause();
            mPausedByTransientLossOfFocus = false;
        }

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

        @Override
        public void onSeekTo(long pos) {
            seek(pos);
        }

        @Override
        public void onSkipToNext() {
            gotoNext(true);
        }

        @Override
        public void onSkipToPrevious() {
            prev(false);
        }

        @Override
        public void onStop() {
            pause();
            mPausedByTransientLossOfFocus = false;
            seek(0);
            releaseServiceUiAndStop();
        }
    });
    mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
}

From source file:org.chromium.chrome.browser.media.ui.MediaNotificationManager.java

private MediaSessionCompat createMediaSession() {
    MediaSessionCompat mediaSession = new MediaSessionCompat(mContext, mContext.getString(R.string.app_name),
            new ComponentName(mContext.getPackageName(), getButtonReceiverClassName()), null);
    mediaSession.setFlags(//from   w w w  .j  a  v a 2 s .c  o m
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(mMediaSessionCallback);

    // TODO(mlamouri): the following code is to work around a bug that hopefully
    // MediaSessionCompat will handle directly. see b/24051980.
    try {
        mediaSession.setActive(true);
    } catch (NullPointerException e) {
        // Some versions of KitKat do not support AudioManager.registerMediaButtonIntent
        // with a PendingIntent. They will throw a NullPointerException, in which case
        // they should be able to activate a MediaSessionCompat with only transport
        // controls.
        mediaSession.setActive(false);
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mediaSession.setActive(true);
    }
    return mediaSession;
}

From source file:com.wojtechnology.sunami.TheBrain.java

private void registerAudio() {
    if (mHasAudioFocus || !mIsInit) {
        return;/*  w ww.ja v a 2 s.c om*/
    }
    mHasAudioFocus = true;

    // Add audio focus change listener
    mAFChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                pausePlayback();
                setUI(false);
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                // Does nothing cause made me play music at work
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                pausePlayback();
                unregisterAudio();
                setUI(false);
            }
        }
    };

    mAudioManager.requestAudioFocus(mAFChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // Add headphone out listener
    registerReceiver(mNoisyAudioStreamReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));

    // Add notification and transport controls
    ComponentName eventReceiver = new ComponentName(getPackageName(),
            RemoteControlEventReceiver.class.getName());
    mSession = new MediaSessionCompat(this, "FireSession", eventReceiver, null);
    mSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    mSession.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
    mSession.setMetadata(new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_TITLE, "")
            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, "")
            .putLong(MediaMetadata.METADATA_KEY_DURATION, -1).build());

    mSession.setCallback(new MediaSessionCompat.Callback() {

        @Override
        public void onSeekTo(long pos) {
            super.onSeekTo(pos);
            setProgress((int) pos, isPlaying());
        }
    });
    mSession.setActive(true);
}

From source file:org.runbuddy.tomahawk.services.PlaybackService.java

private void initMediaSession() {
    ComponentName componentName = new ComponentName(this, MediaButtonReceiver.class);
    mMediaSession = new MediaSessionCompat(getApplicationContext(), "Tomahawk", componentName, null);
    mMediaSession.setFlags(//from  w  ww . j a v  a2  s.  co  m
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    Intent intent = new Intent(PlaybackService.this, TomahawkMainActivity.class);
    intent.setAction(TomahawkMainActivity.SHOW_PLAYBACKFRAGMENT_ON_STARTUP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(PlaybackService.this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mMediaSession.setSessionActivity(pendingIntent);
    HandlerThread thread = new HandlerThread("playbackservice_callback");
    thread.start();
    mCallbackHandler = new Handler(thread.getLooper());
    mMediaSession.setCallback(mMediaSessionCallback, mCallbackHandler);
    mMediaSession.setRatingType(RatingCompat.RATING_HEART);
    Bundle extras = new Bundle();
    extras.putString(EXTRAS_KEY_PLAYBACKMANAGER, mPlaybackManager.getId());
    mMediaSession.setExtras(extras);
    updateMediaPlayState();
    setSessionToken(mMediaSession.getSessionToken());
}

From source file:dk.nota.lyt.libvlc.PlaybackService.java

private void initMediaSession() {
    ComponentName mediaButtonEventReceiver = new ComponentName(this, RemoteControlEventReceiver.class);
    mSessionCallback = new MediaSessionCallback();
    mMediaSession = new MediaSessionCompat(this, "Lyt", mediaButtonEventReceiver, null);
    mMediaSession.setFlags(//from w  w w  .j a  v  a 2  s  .  c  om
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mMediaSession.setCallback(mSessionCallback);
    try {
        mMediaSession.setActive(true);
    } catch (NullPointerException e) {
        // Some versions of KitKat do not support AudioManager.registerMediaButtonIntent
        // with a PendingIntent. They will throw a NullPointerException, in which case
        // they should be able to activate a MediaSessionCompat with only transport controls.
        mMediaSession.setActive(false);
        mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mMediaSession.setActive(true);
    }
}