Search in sources :

Example 16 with MediaSessionCompat

use of android.support.v4.media.session.MediaSessionCompat in project zype-android by zype.

the class VideoCastManager method setUpMediaSession.

/*
     * Sets up the {@link MediaSessionCompat} for this application. It also handles the audio
     * focus.
     */
@SuppressLint("InlinedApi")
private void setUpMediaSession(final MediaInfo info) {
    if (!isFeatureEnabled(BaseCastManager.FEATURE_LOCKSCREEN)) {
        return;
    }
    if (mMediaSessionCompat == null) {
        mMediaEventReceiver = new ComponentName(mContext, VideoIntentReceiver.class.getName());
        mMediaSessionCompat = new MediaSessionCompat(mContext, "TAG", mMediaEventReceiver, 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)) {
                    try {
                        togglePlayback();
                    } catch (CastException | TransientNetworkDisconnectionException | NoConnectionException e) {
                        LOGE(TAG, "onMediaButtonEvent(): Failed to toggle playback", e);
                    }
                }
                return true;
            }
        });
    }
    mAudioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
    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);
}
Also used : KeyEvent(android.view.KeyEvent) Builder(com.google.android.gms.cast.Cast.CastOptions.Builder) ComponentName(android.content.ComponentName) Intent(android.content.Intent) MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat) SuppressLint(android.annotation.SuppressLint)

Example 17 with MediaSessionCompat

use of android.support.v4.media.session.MediaSessionCompat in project ListenerMusicPlayer by hefuyicoder.

the class MusicService method setUpMediaSession.

/**
     * 初始化和设置MediaSessionCompat
     * MediaSessionCompat用于告诉系统及其他应用当前正在播放的内容,以及接收什么类型的播放控制
     */
private void setUpMediaSession() {
    mSession = new MediaSessionCompat(this, "Listener");
    mSession.setCallback(new MediaSessionCompat.Callback() {

        @Override
        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);
}
Also used : MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat)

Example 18 with MediaSessionCompat

use of android.support.v4.media.session.MediaSessionCompat in project AndroidChromium by JackyAndroid.

the class MediaNotificationManager method createMediaSession.

private MediaSessionCompat createMediaSession() {
    MediaSessionCompat mediaSession = new MediaSessionCompat(mContext, mContext.getString(R.string.app_name), new ComponentName(mContext.getPackageName(), getButtonReceiverClassName()), null);
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(mMediaSessionCallback);
    // 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;
}
Also used : ComponentName(android.content.ComponentName) MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat)

Example 19 with MediaSessionCompat

use of android.support.v4.media.session.MediaSessionCompat in project android-UniversalMusicPlayer by googlesamples.

the class MusicService method onCreate.

/*
     * (non-Javadoc)
     * @see android.app.Service#onCreate()
     */
@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");
    mMusicProvider = new MusicProvider();
    // To make the app more responsive, fetch and cache catalog information now.
    // This can help improve the response time in the method
    // {@link #onLoadChildren(String, Result<List<MediaItem>>) onLoadChildren()}.
    mMusicProvider.retrieveMediaAsync(null);
    mPackageValidator = new PackageValidator(this);
    QueueManager queueManager = new QueueManager(mMusicProvider, getResources(), new QueueManager.MetadataUpdateListener() {

        @Override
        public void onMetadataChanged(MediaMetadataCompat metadata) {
            mSession.setMetadata(metadata);
        }

        @Override
        public void onMetadataRetrieveError() {
            mPlaybackManager.updatePlaybackState(getString(R.string.error_no_metadata));
        }

        @Override
        public void onCurrentQueueIndexUpdated(int queueIndex) {
            mPlaybackManager.handlePlayRequest();
        }

        @Override
        public void onQueueUpdated(String title, List<MediaSessionCompat.QueueItem> newQueue) {
            mSession.setQueue(newQueue);
            mSession.setQueueTitle(title);
        }
    });
    LocalPlayback playback = new LocalPlayback(this, mMusicProvider);
    mPlaybackManager = new PlaybackManager(this, getResources(), mMusicProvider, queueManager, playback);
    // Start a new MediaSession
    mSession = new MediaSessionCompat(this, "MusicService");
    setSessionToken(mSession.getSessionToken());
    mSession.setCallback(mPlaybackManager.getMediaSessionCallback());
    mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    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);
    WearHelper.setSlotReservationFlags(mSessionExtras, true, true);
    WearHelper.setUseBackgroundFromTheme(mSessionExtras, true);
    mSession.setExtras(mSessionExtras);
    mPlaybackManager.updatePlaybackState(null);
    try {
        mMediaNotificationManager = new MediaNotificationManager(this);
    } catch (RemoteException e) {
        throw new IllegalStateException("Could not create a MediaNotificationManager", e);
    }
    int playServicesAvailable = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
    if (!TvHelper.isTvUiMode(this) && playServicesAvailable == ConnectionResult.SUCCESS) {
        mCastSessionManager = CastContext.getSharedInstance(this).getSessionManager();
        mCastSessionManagerListener = new CastSessionManagerListener();
        mCastSessionManager.addSessionManagerListener(mCastSessionManagerListener, CastSession.class);
    }
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
    registerCarConnectionReceiver();
}
Also used : Context(android.content.Context) CastContext(com.google.android.gms.cast.framework.CastContext) MediaMetadataCompat(android.support.v4.media.MediaMetadataCompat) Bundle(android.os.Bundle) PlaybackManager(com.example.android.uamp.playback.PlaybackManager) LocalPlayback(com.example.android.uamp.playback.LocalPlayback) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat) QueueManager(com.example.android.uamp.playback.QueueManager) PendingIntent(android.app.PendingIntent) MusicProvider(com.example.android.uamp.model.MusicProvider) RemoteException(android.os.RemoteException)

Example 20 with MediaSessionCompat

use of android.support.v4.media.session.MediaSessionCompat in project Shuttle by timusus.

the class MusicNotificationHelper method getBuilder.

public NotificationCompat.Builder getBuilder(Context context, @NonNull Song song, @NonNull MediaSessionCompat mediaSessionCompat, @Nullable Bitmap bitmap, boolean isPlaying, boolean isFavorite) {
    Intent intent = new Intent(BuildConfig.APPLICATION_ID + ".PLAYBACK_VIEWER");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID).setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(contentIntent).setChannelId(NOTIFICATION_CHANNEL_ID).setPriority(NotificationCompat.PRIORITY_MAX).setContentTitle(song.name).setContentText(song.artistName + " - " + song.albumName).setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle().setShowActionsInCompactView(0, 1, 2).setMediaSession(mediaSessionCompat.getSessionToken())).addAction(R.drawable.ic_skip_previous_24dp, context.getString(R.string.btn_prev), MusicService.retrievePlaybackAction(context, MusicService.ServiceCommand.PREV_ACTION)).addAction(isPlaying ? R.drawable.ic_pause_24dp : R.drawable.ic_play_24dp, context.getString(isPlaying ? R.string.btn_pause : R.string.btn_play), MusicService.retrievePlaybackAction(context, MusicService.ServiceCommand.TOGGLE_PAUSE_ACTION)).addAction(R.drawable.ic_skip_next_24dp, context.getString(R.string.btn_skip), MusicService.retrievePlaybackAction(context, MusicService.ServiceCommand.NEXT_ACTION)).addAction(isFavorite ? R.drawable.ic_favorite_24dp_scaled : R.drawable.ic_favorite_border_24dp_scaled, context.getString(R.string.fav_add), MusicService.retrievePlaybackAction(context, MusicService.ServiceCommand.TOGGLE_FAVORITE)).setShowWhen(false).setVisibility(android.support.v4.app.NotificationCompat.VISIBILITY_PUBLIC);
    if (bitmap != null) {
        builder.setLargeIcon(bitmap);
    }
    return builder;
}
Also used : NotificationCompat(android.support.v4.app.NotificationCompat) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent)

Aggregations

MediaSessionCompat (android.support.v4.media.session.MediaSessionCompat)31 Intent (android.content.Intent)17 PendingIntent (android.app.PendingIntent)16 ComponentName (android.content.ComponentName)10 PlaybackStateCompat (android.support.v4.media.session.PlaybackStateCompat)8 MediaMetadataCompat (android.support.v4.media.MediaMetadataCompat)5 Bundle (android.os.Bundle)4 Context (android.content.Context)3 NotificationCompat (android.support.v4.app.NotificationCompat)3 MediaControllerCompat (android.support.v4.media.session.MediaControllerCompat)3 KeyEvent (android.view.KeyEvent)3 SuppressLint (android.annotation.SuppressLint)2 NotificationManager (android.app.NotificationManager)2 IntentFilter (android.content.IntentFilter)2 Bitmap (android.graphics.Bitmap)2 NonNull (android.support.annotation.NonNull)2 Builder (com.google.android.gms.cast.Cast.CastOptions.Builder)2 NotificationChannel (android.app.NotificationChannel)1 SharedPreferences (android.content.SharedPreferences)1 Canvas (android.graphics.Canvas)1