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.doctoror.fuckoffmusicplayer.data.media.session.MediaSessionFactoryImpl.java

@NonNull
@Override//from  w w  w.  ja  va 2  s.  c  o m
public MediaSessionCompat newMediaSession() {
    final MediaSessionCompat mediaSession = new MediaSessionCompat(context, TAG_MEDIA_SESSION,
            mediaButtonReceiver, mediaButtonIntent);
    mediaSession.setCallback(mediaSessionCallback);
    mediaSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setSessionActivity(PendingIntent.getActivity(context, 1,
            new Intent(context, sessionActivityClass), PendingIntent.FLAG_UPDATE_CURRENT));
    mediaSession.setActive(true);
    return mediaSession;
}

From source file:org.interactiverobotics.headset_launcher.MediaButtonMonitorService.java

@Override
public void onCreate() {

    Log.d(TAG, "Create");

    //   ?   //from ww  w  .j a v a2 s .  c  o m

    mMediaButtonReceiver = new ComponentName(this, MediaButtonReceiver.class);

    // ,  ?   API 18+
    //
    //        final Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    //
    //        mediaButtonIntent.setComponent(mMediaButtonReceiver);
    //
    //        mPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);

    mMediaSession = new MediaSessionCompat(this, TAG, mMediaButtonReceiver, /* pendingIntent */ null);

    mMediaSession.setCallback(new MediaSessionCompat.Callback() {

        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonEvent) {

            if (Intent.ACTION_MEDIA_BUTTON.equals(mediaButtonEvent.getAction())) {

                final KeyEvent keyEvent = (KeyEvent) mediaButtonEvent
                        .getParcelableExtra(Intent.EXTRA_KEY_EVENT);

                if (KeyEvent.KEYCODE_HEADSETHOOK == keyEvent.getKeyCode()) {

                    if (KeyEvent.ACTION_DOWN == keyEvent.getAction()) {

                        Log.d(TAG, "Media button down!");

                        // ? 

                        startService(new Intent(MediaButtonMonitorService.this, LauncherService.class));
                    }

                } else {

                    Log.e(TAG, "Unknown keycode: " + keyEvent.getKeyCode());
                }

            } else {

                Log.e(TAG, "Unknown intent: " + mediaButtonEvent.getAction());
            }

            return true;
        }

    });

    mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);

    mMediaSession.setActive(true);
}

From source file:com.devbrackets.android.exomedia.EMLockScreen.java

/**
 * Creates a new EMLockScreen object/*from   ww  w. j  av  a 2 s  .c o  m*/
 *
 * @param context The context to use for holding a MediaSession and sending action intents
 * @param mediaServiceClass The class for the service that owns the backing MediaService and to notify of playback actions
 */
public EMLockScreen(Context context, Class<? extends Service> mediaServiceClass) {
    this.context = context;
    this.mediaServiceClass = mediaServiceClass;

    ComponentName componentName = new ComponentName(context, MediaControlsReceiver.class.getName());

    mediaSession = new MediaSessionCompat(context, SESSION_TAG, componentName,
            getMediaButtonReceiverPendingIntent(componentName));
    mediaSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(new SessionCallback());
}

From source file:com.devbrackets.android.playlistcore.helper.MediaControlsHelper.java

/**
 * Creates a new MediaControlsHelper object
 *
 * @param context The context to use for holding a MediaSession and sending action intents
 * @param mediaServiceClass The class for the service that owns the backing MediaService and to notify of playback actions
 *//*from ww w  .ja  v  a  2 s.com*/
public MediaControlsHelper(@NonNull Context context, @NonNull Class<? extends Service> mediaServiceClass) {
    this.context = context;

    ComponentName componentName = new ComponentName(context, MediaControlsReceiver.class.getName());

    mediaSession = new MediaSessionCompat(context, SESSION_TAG, componentName,
            getMediaButtonReceiverPendingIntent(componentName, mediaServiceClass));
    mediaSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(new SessionCallback(mediaServiceClass));
}

From source file:com.mylovemhz.simplay.MusicService.java

private void initialize() {
    trackQueue = new ArrayList<>();

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL,
            "music lock");

    ComponentName receiver = new ComponentName(getPackageName(), MediaButtonEventReceiver.class.getName());
    mediaSession = new MediaSessionCompat(this, TAG_MUSIC_SERVICE, receiver, null);
    mediaSession.setFlags(//w  w w . j  ava2 s  .c o  m
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(new SimpleSessionCallback(this));

    currentState = State.IDLE;
    mediaSession.setActive(true);

    isInitialized = true;
    Log.d(TAG_MUSIC_SERVICE, "Initialized...");
}

From source file:com.somexapps.wyre.services.MediaService.java

private void initMediaSessions() {
    // Initialize player
    mediaPlayer = new MediaPlayer();

    // Add listener to handle completion of song
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override/*  w  w w. j  av a  2  s  .co m*/
        public void onCompletion(MediaPlayer mp) {
            // Send intent to play next song in MediaService list
            Intent nextSong = new Intent(getApplicationContext(), MediaService.class);
            nextSong.setAction(ACTION_NEXT);
            startService(nextSong);
        }
    });

    // Set up session and controller
    // Create the media session
    mediaSession = new MediaSessionCompat(this, MEDIA_SESSION_TAG, mediaSessionComponentName, null);

    // Set up controller
    try {
        mediaController = new MediaControllerCompat(getApplicationContext(), mediaSession.getSessionToken());
    } catch (RemoteException e) {
        Log.e(TAG, "Unable to set up media controller: " + e.getMessage());
    }

    // Set up callbacks for media session
    mediaSession.setCallback(new MediaSessionCompat.Callback() {
        @Override
        public void onPlay() {
            super.onPlay();
            Log.d(TAG, "Playing media");
            buildNotification(generateAction(R.drawable.ic_pause_white_36dp,
                    getString(R.string.media_service_notification_pause), ACTION_PAUSE));
        }

        @Override
        public void onPause() {
            super.onPause();
            Log.d(TAG, "Pausing media");
            buildNotification(generateAction(R.drawable.ic_play_arrow_white_36dp,
                    getString(R.string.media_service_notification_play), ACTION_PLAY));
        }

        @Override
        public void onSkipToNext() {
            super.onSkipToNext();
            Log.d(TAG, "Skipping to next song");

            // Update the notification with the next song info
            buildNotification(generateAction(R.drawable.ic_pause_white_36dp,
                    getString(R.string.media_service_notification_pause), ACTION_PAUSE));
        }

        @Override
        public void onSkipToPrevious() {
            super.onSkipToPrevious();
            Log.d(TAG, "Skipping to previous song");

            // Update the notification with the previous song info
            buildNotification(generateAction(R.drawable.ic_pause_white_36dp,
                    getString(R.string.media_service_notification_pause), ACTION_PAUSE));
        }

        @Override
        public void onFastForward() {
            super.onFastForward();
        }

        @Override
        public void onRewind() {
            super.onRewind();
        }

        @Override
        public void onStop() {
            super.onStop();
        }

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

        @Override
        public void onSetRating(RatingCompat rating) {
            super.onSetRating(rating);
        }
    });
}

From source file:com.teocci.utubinbg.BackgroundAudioService.java

/**
 * Initializes media sessions and receives media events
 *//*from w  ww. j av a2s  . c o  m*/
private void initMediaSessions() {
    // Make sure the media player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    //
    // Remember that to use this, we have to declare the android.permission.WAKE_LOCK
    // permission in AndroidManifest.xml.
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

    ComponentName eventReceiver = new ComponentName(getApplicationContext().getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    PendingIntent buttonReceiverIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent(Intent.ACTION_MEDIA_BUTTON), PendingIntent.FLAG_UPDATE_CURRENT);

    mSession = new MediaSessionCompat(getApplicationContext(), "simple player session", eventReceiver,
            buttonReceiverIntent);

    try {
        mController = new MediaControllerCompat(getApplicationContext(), mSession.getSessionToken());

        mSession.setCallback(new MediaSessionCompat.Callback() {
            @Override
            public void onPlay() {
                super.onPlay();
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onPause() {

                super.onPause();
                pauseVideo();
                buildNotification(generateAction(android.R.drawable.ic_media_play, "Play", ACTION_PLAY));
            }

            @Override
            public void onSkipToNext() {
                super.onSkipToNext();
                if (!isStarting) {
                    playNext();
                }
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onSkipToPrevious() {
                super.onSkipToPrevious();
                if (!isStarting) {
                    playPrevious();
                }
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onStop() {
                super.onStop();
                stopPlayer();
                //remove notification and stop service
                NotificationManager notificationManager = (NotificationManager) getApplicationContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancel(1);
                Intent intent = new Intent(getApplicationContext(), BackgroundAudioService.class);
                stopService(intent);
            }

            @Override
            public void onSetRating(RatingCompat rating) {
                super.onSetRating(rating);
            }
        });
    } catch (RemoteException re) {
        re.printStackTrace();
    }
}

From source file:com.example.android.mediabrowserservice.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    LogHelper.d(TAG, "onCreate");

    mPlayingQueue = new ArrayList<>();
    mMusicProvider = new MusicProvider();
    mPackageValidator = new PackageValidator(this);

    // Start a new MediaSession
    mSession = new MediaSessionCompat(this, "MusicService",
            new ComponentName(this, MediaNotificationManager.class), null);
    setSessionToken(mSession.getSessionToken());
    mSession.setCallback(new MediaSessionCallback());
    mSession.setFlags(/*from   w  w  w  .  j a  v a  2 s  .  co  m*/
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);

    mPlayback = new Playback(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);

    Bundle extras = new Bundle();
    CarHelper.setSlotReservationFlags(extras, true, true, true);
    mSession.setExtras(extras);

    updatePlaybackState(null);

    mMediaNotificationManager = new MediaNotificationManager(this);
}

From source file:nuclei.media.MediaService.java

@Override
public void onCreate() {
    super.onCreate();
    LOG.d("onCreate");

    mPackageValidator = new PackageValidator(this);

    boolean casting = false;
    try {/*from w  w  w . j av  a2 s  . co m*/
        VideoCastManager.getInstance().addVideoCastConsumer(mCastConsumer);
        casting = VideoCastManager.getInstance().isConnected() || VideoCastManager.getInstance().isConnecting();
    } catch (IllegalStateException err) {
        LOG.e("Error registering cast consumer : " + err.getMessage());
    }

    Playback playback;

    // Start a new MediaSession
    mSession = new MediaSessionCompat(this, "NucleiMediaService",
            new ComponentName(getApplicationContext(), MediaButtonReceiver.class), null);
    mSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);

    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
    setSessionToken(mSession.getSessionToken());

    try {
        mMediaNotificationManager = new MediaNotificationManager(this);
    } catch (RemoteException e) {
        throw new IllegalStateException("Could not create a MediaNotificationManager", e);
    }

    mSessionExtras = new Bundle();

    if (casting) {
        mSessionExtras.putString(EXTRA_CONNECTED_CAST, VideoCastManager.getInstance().getDeviceName());
        mMediaRouter.setMediaSessionCompat(mSession);
        playback = PlaybackFactory.createCastPlayback(MediaService.this);
    } else
        playback = PlaybackFactory.createLocalPlayback(MediaService.this);

    mPlaybackManager = new PlaybackManager(this, playback);

    mSession.setCallback(mPlaybackManager.getMediaSessionCallback());

    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(new ComponentName(this, MediaService.class));
    mSession.setMediaButtonReceiver(PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0));

    CarHelper.setSlotReservationFlags(mSessionExtras, true, true, true);
    mSession.setExtras(mSessionExtras);

    mPlaybackManager.updatePlaybackState(null, true);

    registerCarConnectionReceiver();
}

From source file:com.smedic.tubtub.BackgroundAudioService.java

/**
 * Initializes media sessions and receives media events
 */// ww w. j a v  a 2 s  .co m
private void initMediaSessions() {
    PendingIntent buttonReceiverIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent(Intent.ACTION_MEDIA_BUTTON), PendingIntent.FLAG_UPDATE_CURRENT);

    mSession = new MediaSessionCompat(getApplicationContext(), "simple player session", null,
            buttonReceiverIntent);

    try {
        mController = new MediaControllerCompat(getApplicationContext(), mSession.getSessionToken());

        mSession.setCallback(new MediaSessionCompat.Callback() {
            @Override
            public void onPlay() {
                super.onPlay();
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onPause() {

                super.onPause();
                pauseVideo();
                buildNotification(generateAction(android.R.drawable.ic_media_play, "Play", ACTION_PLAY));
            }

            @Override
            public void onSkipToNext() {
                super.onSkipToNext();
                playNext();
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onSkipToPrevious() {
                super.onSkipToPrevious();
                playPrevious();
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onStop() {
                super.onStop();
                stopPlayer();
                //remove notification and stop service
                NotificationManager notificationManager = (NotificationManager) getApplicationContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancel(1);
                Intent intent = new Intent(getApplicationContext(), BackgroundAudioService.class);
                stopService(intent);
            }

            @Override
            public void onSetRating(RatingCompat rating) {
                super.onSetRating(rating);
            }
        });
    } catch (RemoteException re) {
        re.printStackTrace();
    }
}