Hussain ID
Hussain ID

Reputation: 231

How to control music playing in service from notification and lockscreen

Please show me the code that controls the media player (Streaming mp3 from server) from notification and lock screen. I know that's really simple, but i don't know from where to start. I actually doesn't know more about mediaController ,mediaSessionCompat and NotifacationCompat.MediaStyle.

Please refer a code to do say. I just want to play/pause and icon that closes the icon.

Thank your very very much in advance.

Upvotes: 3

Views: 5722

Answers (1)

Sapan Diwakar
Sapan Diwakar

Reputation: 10946

The first thing you need is to register a Media Session and set a callback to receive events from the lock screen.

mSession = new MediaSession(this, "MusicService");
mSession.setCallback(new MediaSessionCallback());
mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);

Create a notification

Notification.Builder notificationBuilder = new Notification.Builder(mService);
notificationBuilder
        .setStyle(new Notification.MediaStyle()
            .setShowActionsInCompactView(new int[]{playPauseButtonPosition})  // show only play/pause in compact view
            .setMediaSession(mSessionToken))
        .setColor(mNotificationColor)
        .setSmallIcon(R.drawable.ic_notification)
        .setVisibility(Notification.VISIBILITY_PUBLIC)
        .setUsesChronometer(true)
        .setContentIntent(createContentIntent(description)) // Create an intent that would open the UI when user clicks the notification
        .setContentTitle(description.getTitle())
        .setContentText(description.getSubtitle())
        .setLargeIcon(art).build()

Add actions using addAction

Notification notification = createNotification();
if (notification != null) {
    mController.registerCallback(mCb);
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_NEXT);
    filter.addAction(ACTION_PAUSE);
    filter.addAction(ACTION_PLAY);
    filter.addAction(ACTION_PREV);
    mService.registerReceiver(this, filter);

    mService.startForeground(NOTIFICATION_ID, notification);
    mStarted = true;
}

Here's a tutorial about Android Music Player Controls on Lock Screen and Notifications

Upvotes: 3

Related Questions