如何通过通知和锁屏控制在服务中播放的音乐

时间:2016-02-21 09:34:10

标签: android

请告诉我控制媒体播放器的代码(来自服务器的流媒体播放)来自通知和锁定屏幕。我知道这很简单,但我不知道从哪里开始。我实际上并不了解mediaControllermediaSessionCompatNotifacationCompat.MediaStyle的更多信息。

请参考代码来说。我只想玩/暂停和关闭图标的图标。

提前非常感谢你。

1 个答案:

答案 0 :(得分:2)

首先需要注册媒体会话并设置回调以从锁定屏幕接收事件。

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

创建通知

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()

使用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;
}

以下是关于Android Music Player Controls on Lock Screen and Notifications

的教程