Search in sources :

Example 1 with MediaSessionCompat

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

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(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 (CastException | TransientNetworkDisconnectionException | 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);
}
Also used : KeyEvent(android.view.KeyEvent) PlaybackStateCompat(android.support.v4.media.session.PlaybackStateCompat) Builder(com.google.android.gms.cast.Cast.CastOptions.Builder) ComponentName(android.content.ComponentName) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat) VideoIntentReceiver(com.google.android.libraries.cast.companionlibrary.remotecontrol.VideoIntentReceiver) SuppressLint(android.annotation.SuppressLint)

Example 2 with MediaSessionCompat

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

the class PlaybackService method initMediaSession.

private void initMediaSession() {
    final Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setClass(this, RemoteControlClientReceiver.class);
    final PendingIntent mbrIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);
    final ComponentName mbrName = new ComponentName(this, RemoteControlClientReceiver.class);
    mSessionCallback = new MediaSessionCallback();
    mMediaSession = new MediaSessionCompat(this, "VLC", mbrName, mbrIntent);
    mMediaSession.setFlags(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);
    }
    setSessionToken(mMediaSession.getSessionToken());
}
Also used : PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) ComponentName(android.content.ComponentName) PendingIntent(android.app.PendingIntent) MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat)

Example 3 with MediaSessionCompat

use of android.support.v4.media.session.MediaSessionCompat in project PainlessMusicPlayer by Doctoror.

the class PlaybackNotificationFactoryImpl method create.

@NonNull
@Override
public Notification create(@NonNull final Context context, @NonNull final Media media, @PlaybackState final int state, @NonNull final MediaSessionCompat mediaSession) {
    ensureChannelExists(context);
    final Bitmap art = loadAlbumArt(context, media);
    final PendingIntent contentIntent = createContentIntent(context);
    final NotificationCompat.Style style = createNotificationStyle(mediaSession);
    final NotificationCompat.Builder b = new NotificationCompat.Builder(context, CHANNEL_ID).setStyle(style).setShowWhen(false).setOnlyAlertOnce(true).setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setCategory(NotificationCompat.CATEGORY_SERVICE).setContentTitle(media.getTitle()).setContentText(media.getArtist()).setContentIntent(contentIntent).setAutoCancel(false).setOngoing(true).setSmallIcon(state == PlaybackState.STATE_PLAYING ? R.drawable.ic_stat_play : R.drawable.ic_stat_pause).setLargeIcon(art);
    addAction1(context, b);
    addAction2(context, b, state);
    addAction3(context, b);
    return b.build();
}
Also used : Bitmap(android.graphics.Bitmap) NotificationCompat(android.support.v4.app.NotificationCompat) PendingIntent(android.app.PendingIntent) NonNull(android.support.annotation.NonNull)

Example 4 with MediaSessionCompat

use of android.support.v4.media.session.MediaSessionCompat in project PainlessMusicPlayer by Doctoror.

the class PlaybackServiceImpl method init.

private void init() {
    acquireWakeLock();
    mMediaPlayer = mMediaPlayerFactory.newMediaPlayer();
    mDestroying = false;
    mErrorMessage = null;
    mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    mMediaSessionHolder.openSession();
    final MediaSessionCompat mediaSession = mMediaSessionHolder.getMediaSession();
    if (mediaSession == null) {
        throw new IllegalStateException("MediaSession is null");
    }
    mPlaybackReporter = mPlaybackReporterFactory.newUniversalReporter(mediaSession);
    mContext.registerReceiver(mBecomingNoisyReceiver, mBecomingNoisyReceiver.mIntentFilter);
    mMediaPlayer.setListener(mMediaPlayerListener);
    mMediaPlayer.init(mContext);
    mDisposableQueue = mPlaybackData.queueObservable().subscribe(new QueueConsumer());
}
Also used : MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat)

Example 5 with MediaSessionCompat

use of android.support.v4.media.session.MediaSessionCompat in project AndroidAudioExample by SergeyVinyar.

the class PlayerService method onCreate.

@Override
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_DEFAULT_CHANNEL_ID, getString(R.string.notification_channel_name), NotificationManagerCompat.IMPORTANCE_DEFAULT);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
        AudioAttributes audioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
        audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN).setOnAudioFocusChangeListener(audioFocusChangeListener).setAcceptsDelayedFocusGain(false).setWillPauseWhenDucked(true).setAudioAttributes(audioAttributes).build();
    }
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mediaSession = new MediaSessionCompat(this, "PlayerService");
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(mediaSessionCallback);
    Context appContext = getApplicationContext();
    Intent activityIntent = new Intent(appContext, MainActivity.class);
    mediaSession.setSessionActivity(PendingIntent.getActivity(appContext, 0, activityIntent, 0));
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null, appContext, MediaButtonReceiver.class);
    mediaSession.setMediaButtonReceiver(PendingIntent.getBroadcast(appContext, 0, mediaButtonIntent, 0));
    exoPlayer = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(this), new DefaultTrackSelector(), new DefaultLoadControl());
    exoPlayer.addListener(exoPlayerListener);
    DataSource.Factory httpDataSourceFactory = new OkHttpDataSourceFactory(new OkHttpClient(), Util.getUserAgent(this, getString(R.string.app_name)), null);
    // 100 Mb max
    Cache cache = new SimpleCache(new File(this.getCacheDir().getAbsolutePath() + "/exoplayer"), new LeastRecentlyUsedCacheEvictor(1024 * 1024 * 100));
    this.dataSourceFactory = new CacheDataSourceFactory(cache, httpDataSourceFactory, CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR);
    this.extractorsFactory = new DefaultExtractorsFactory();
}
Also used : Context(android.content.Context) DefaultExtractorsFactory(com.google.android.exoplayer2.extractor.DefaultExtractorsFactory) OkHttpClient(okhttp3.OkHttpClient) NotificationManager(android.app.NotificationManager) LeastRecentlyUsedCacheEvictor(com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor) AudioAttributes(android.media.AudioAttributes) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat) DefaultLoadControl(com.google.android.exoplayer2.DefaultLoadControl) DataSource(com.google.android.exoplayer2.upstream.DataSource) CacheDataSource(com.google.android.exoplayer2.upstream.cache.CacheDataSource) NotificationChannel(android.app.NotificationChannel) SimpleCache(com.google.android.exoplayer2.upstream.cache.SimpleCache) CacheDataSourceFactory(com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory) DefaultTrackSelector(com.google.android.exoplayer2.trackselection.DefaultTrackSelector) OkHttpDataSourceFactory(com.google.android.exoplayer2.ext.okhttp.OkHttpDataSourceFactory) DefaultRenderersFactory(com.google.android.exoplayer2.DefaultRenderersFactory) File(java.io.File) Cache(com.google.android.exoplayer2.upstream.cache.Cache) SimpleCache(com.google.android.exoplayer2.upstream.cache.SimpleCache)

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