我正在构建一个音频播放器。为此,我实现了一个后台服务。现在,我正在尝试使用 mediasession 将音频的专辑封面显示为锁屏壁纸。我已经成功实现了锁屏播放控件和通知,但我无法将专辑封面显示为锁屏壁纸。
我正在使用的代码:
private void initMediaSession() throws RemoteException {
if (mediaSessionManager != null) return; //mediaSessionManager exists
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
}
// Create a new MediaSession
mediaSession = new MediaSessionCompat(this, "AudioPlayer");
//Get MediaSessions transport controls
transportControls = mediaSession.getController().getTransportControls();
//set MediaSession -> ready to receive media commands
mediaSession.setActive(true);
//indicate that the MediaSession handles transport control commands
// through its MediaSessionCompat.Callback.
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS|MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
//Set mediaSession's MetaData
updateMetaData();
mediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public void onPlay() {
super.onPlay();
resumeMedia();
}
@Override
public void onPause() {
super.onPause();
pauseMedia();
}
@Override
public void onSkipToNext() {
super.onSkipToNext();
skipToNext();
}
@Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
skipToPrevious();
}
});
}
private void updateMetaData() {
// Update the current metadata
metaDataBuilder = new MediaMetadataCompat.Builder();
// Bitmap bitmap =BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, songInfoModelService.getArtistName())
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, songInfoModelService.getSongName());
Glide.with(this).asBitmap().load(songInfoModelService.getAlbumIDArtwork()).into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
metaDataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ART,resource);
metaDataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, resource);
mediaSession.setMetadata(metaDataBuilder.build());
}
});
}`