MediaControllerCompat的getMetadata返回null

时间:2019-12-17 03:40:30

标签: android mediacontroller android-mediasession mediabrowserservicecompat

我正在尝试使用this视频作为指南在Android中制作音频应用,但是在使用音频的元数据创建通知时遇到了麻烦。

这是我用来从设备中提取音频文件的代码:

public void loadData() {
    ContentResolver contentResolver = context.getContentResolver();

    String selection = Media.IS_MUSIC + "!= 0";
    String[] projection = {
        Media._ID,
        Media.ARTIST,
        Media.TITLE,
        Media.DISPLAY_NAME,
        Media.DURATION,
        Media.ALBUM
    };

    Cursor cursor = contentResolver.query(
        Media.EXTERNAL_CONTENT_URI, projection, selection, null, null
    );

    if(cursor == null || !cursor.moveToFirst()) return;
    else {
        int size = cursor.getCount();
        metadata = new ArrayList<>(size);
        mediaItems = new ArrayList<>(size);
    }

    int
        idIndex          = cursor.getColumnIndex(Media._ID),
        artistIndex      = cursor.getColumnIndex(Media.ARTIST),
        titleIndex       = cursor.getColumnIndex(Media.TITLE),
        displayNameIndex = cursor.getColumnIndex(Media.DISPLAY_NAME),
        durationIndex    = cursor.getColumnIndex(Media.DURATION),
        albumIndex       = cursor.getColumnIndex(Media.ALBUM);

    do {
        String mediaId = cursor.getString(idIndex);
        MediaMetadataCompat data = new MediaMetadataCompat.Builder()
            .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, cursor.getString(idIndex))
            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, cursor.getString(albumIndex))
            .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, cursor.getString(artistIndex))
            .putString(MediaMetadataCompat.METADATA_KEY_TITLE, cursor.getString(titleIndex))
            .putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, cursor.getString(displayNameIndex))
            .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, cursor.getLong(durationIndex))
            .build();

        metadata.add(data);
        mediaItems.add(new MediaBrowserCompat.MediaItem(
            data.getDescription(),
            MediaItem.FLAG_PLAYABLE
        ));
    } while(cursor.moveToNext());

    cursor.close();
}

public List<MediaItem> getMediaItems() {
    return mediaItems;
}

这是我的MediaBrowserService的onLoadChildren代码:

@Override
public void onLoadChildren(@NonNull String parentId,
                           @NonNull Result<List<MediaBrowserCompat.MediaItem>> result
) {
    if(parentId.equals(MEDIA_ROOT_ID)) {
        result.sendResult(source.getMediaItems());
    }
}

最后,代码抛出错误(在创建MediaSession和setActive(true)之后,我调用createNotifcation()):

private void createNotification() {
    NotificationCompat.Action playAction = new NotificationCompat.Action(
        android.R.drawable.ic_media_play,
        getString(R.string.play),
        MediaButtonReceiver.buildMediaButtonPendingIntent(
            ExoMusicService.this,
            PlaybackStateCompat.ACTION_PLAY
        )
    );
    NotificationCompat.Action pauseAction = new NotificationCompat.Action(
        android.R.drawable.ic_media_pause,
        getString(R.string.pause),
        MediaButtonReceiver.buildMediaButtonPendingIntent(
            ExoMusicService.this,
            PlaybackStateCompat.ACTION_PAUSE
        )
    );
    MediaControllerCompat controller = mediaSession.getController();
    Log.i(LOG_TAG, "createNotification: " + (controller == null)); // false
    MediaMetadataCompat metadata = controller.getMetadata();
    Log.i(LOG_TAG, "createNotification: " + (metadata == null)); // true
    MediaDescriptionCompat description = metadata.getDescription();

    notification = new NotificationCompat.Builder(ExoMusicService.this, PLAYBACK_CHANNEL_ID)
        .setContentTitle(description.getTitle())
        .setContentText(description.getSubtitle())
        .setContentIntent(controller.getSessionActivity())
        .setStyle(
            new MediaStyle()
                .setShowActionsInCompactView(0)
                .setMediaSession(mediaSession.getSessionToken())
                .setShowCancelButton(true)
        )
        .setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(
            ExoMusicService.this,
            PlaybackStateCompat.ACTION_STOP
        ))
        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
        .addAction(playerManager.isPlaying()? pauseAction : playAction)
        .setSmallIcon(R.drawable.icon)
        .build();
}

如果我理解正确,我相信这是与此问题有关的所有代码。 关于我可以忽略的内容有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在显示通知之前,您应该调用mediaSession.setMetadata(/ *您的元数据* /)。

元数据应包含有关正在播放(或准备,暂停等)的当前音乐项目的信息。

有关详细信息,请参阅documentation