在Android 13中,通过通知按钮控制音频播放时,可能出现播放状态回调未被调用的情况。这可能是由于以下原因之一造成的:
以下是解决此问题的一种方法:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = getSystemService(NotificationManager.class);
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Channel name",
NotificationManager.IMPORTANCE_LOW
);
channel.setSound(null, null);
channel.setDescription("Channel description");
notificationManager.createNotificationChannel(channel);
}
MediaSessionCompat mediaSession = new MediaSessionCompat(this, "tag");
mediaSession.setActive(true);
mediaSession.setMetadata(new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, "Title")
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "Artist")
.build());
mediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public void onPlay() {
super.onPlay();
// Start playback here
}
@Override
public void onPause() {
super.onPause();
// Pause playback here
}
@Override
public void onStop() {
super.onStop();
// Stop playback here
}
});
PlaybackStateCompat state = new PlaybackStateCompat.Builder()
.setState(
PlaybackStateCompat.STATE_PLAYING,
PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN,
1.0f
)
.setActions(
PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_STOP
)
.build();
mediaSession.setPlaybackState(state);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSession.getSessionToken())
.setShowActionsInCompactView(0, 1, 2)
.setContentTitle("Title")
.setContentText("Artist")
.setSmallIcon(R.drawable.ic_launcher_background))
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
builder.addAction(new NotificationCompat.Action(
R.drawable.ic_skip_previous,
"Previous