You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android音乐播放器实现带控制按钮与封面的媒体通知求助

实现带控制按钮和专辑封面的媒体播放通知

嘿,我来帮你搞定这个媒体通知的实现!其实Android现在推荐用MediaSession来管理媒体播放会话,这样不仅能创建符合系统规范的通知,还能让你的播放器和系统媒体控件(比如锁屏、通知栏媒体控制)交互。下面我会一步步把代码整合到你的play_ui.java里:

第一步:添加必要的导入

在你的play_ui.java顶部添加这些导入,用来支持媒体会话和通知功能:

import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationManagerCompat;
import androidx.media.app.NotificationCompat.MediaStyle; // 若使用AndroidX,用这个导入

第二步:添加全局成员变量

在play_ui类里添加几个变量,用来管理媒体会话和通知:

private MediaSessionCompat mMediaSession;
private NotificationManagerCompat mNotificationManager;
private static final int NOTIFICATION_ID = 1001; // 通知的唯一标识ID

第三步:初始化MediaSession和通知管理器

在onCreate方法里,初始化MediaSession来处理播放控制回调,同时初始化通知管理器:

// 初始化MediaSession,用于处理媒体控制事件
mMediaSession = new MediaSessionCompat(this, "MusicPlayerSession");
mMediaSession.setFlags(
        MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
        MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
// 设置回调,响应通知栏的播放/暂停/停止按钮点击
mMediaSession.setCallback(new MediaSessionCompat.Callback() {
    @Override
    public void onPlay() {
        super.onPlay();
        if (!mp.isPlaying()) {
            mp.start();
            pause.setBackgroundResource(R.drawable.pause);
            updateNotification(true);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mp.isPlaying()) {
            mp.pause();
            pause.setBackgroundResource(R.drawable.ic_play_arrow_black_24dp);
            updateNotification(false);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mp != null) {
            mp.stop();
            pause.setBackgroundResource(R.drawable.ic_play_arrow_black_24dp);
        }
        mNotificationManager.cancel(NOTIFICATION_ID);
        mMediaSession.release();
    }
});
mMediaSession.setActive(true);

// 初始化通知管理器
mNotificationManager = NotificationManagerCompat.from(this);

第四步:编写通知构建方法

添加一个updateNotification方法,用来根据播放状态创建或更新通知,这里会整合专辑封面和播放控制按钮:

private void updateNotification(boolean isPlaying) {
    // 创建点击通知回到播放器页面的PendingIntent
    Intent intent = new Intent(this, play_ui.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // 根据播放状态生成播放/暂停按钮Action
    NotificationCompat.Action playPauseAction;
    if (isPlaying) {
        playPauseAction = new NotificationCompat.Action(
                R.drawable.ic_pause_black_24dp, // 替换为你的暂停图标
                "暂停",
                MediaSessionCompat.getMediaButtonPendingIntent(this, PlaybackStateCompat.ACTION_PAUSE)
        );
    } else {
        playPauseAction = new NotificationCompat.Action(
                R.drawable.ic_play_arrow_black_24dp, // 替换为你的播放图标
                "播放",
                MediaSessionCompat.getMediaButtonPendingIntent(this, PlaybackStateCompat.ACTION_PLAY)
        );
    }

    // 构建媒体风格通知
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "MUSIC_PLAYER_CHANNEL")
            .setSmallIcon(R.drawable.ic_music_note_black_24dp) // 必须设置的小图标,建议用白色简约样式
            .setContentTitle(songtext.getText()) // 显示当前歌曲名
            .setContentText("正在播放") // 副标题,可自定义内容
            .setLargeIcon(art) // 使用你之前获取的专辑封面Bitmap
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) // 锁屏状态下也能看到通知内容
            .addAction(playPauseAction) // 添加播放/暂停控制按钮
            .setStyle(new MediaStyle() // 使用系统媒体通知样式
                    .setMediaSession(mMediaSession.getSessionToken())
                    .setShowActionsInCompactView(0)); // 在紧凑视图中显示第一个按钮(播放/暂停)

    // Android 8.0+ 必须创建通知渠道
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        android.app.NotificationChannel channel = new android.app.NotificationChannel(
                "MUSIC_PLAYER_CHANNEL",
                "音乐播放器通知",
                android.app.NotificationManager.IMPORTANCE_HIGH
        );
        channel.setDescription显示音乐播放状态和控制按钮();
        mNotificationManager.createNotificationChannel(channel);
    }

    // 显示或更新通知
    mNotificationManager.notify(NOTIFICATION_ID, builder.build());
}

第五步:在播放状态变化时更新通知

  1. 在mp.start()之后调用updateNotification(true),播放开始时显示通知:
mp.start();
updateNotification(true); // 播放启动时显示通知
  1. 修改暂停按钮的点击事件,同步更新通知状态:
pause.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        sb.setMax(mp.getDuration());
        if(mp.isPlaying()){
            pause.setBackgroundResource(R.drawable.ic_play_arrow_black_24dp);
            mp.pause();
            updateNotification(false); // 暂停时更新通知
        } else {
            pause.setBackgroundResource(R.drawable.pause);
            mp.start();
            updateNotification(true); // 继续播放时更新通知
        }
    }
});

第六步:清理资源避免内存泄漏

在Activity销毁时,释放MediaSession并取消通知:

@Override
protected void onDestroy() {
    super.onDestroy();
    // 释放MediaSession资源
    if (mMediaSession != null) {
        mMediaSession.setActive(false);
        mMediaSession.release();
    }
    // 取消通知
    mNotificationManager.cancel(NOTIFICATION_ID);
    // 释放MediaPlayer资源
    if (mp != null) {
        mp.stop();
        mp.release();
        mp = null;
    }
}

一些注意事项

  • 确保你的图标资源(播放、暂停、小图标等)存在,避免因找不到资源崩溃
  • 若项目使用旧版Support库而非AndroidX,将MediaStyle的导入改为android.support.v4.app.NotificationCompat.MediaStyle
  • 通知小图标建议使用白色简约样式,符合Android系统通知规范

这样修改后,你的播放器在播放音乐时就会显示带有专辑封面和播放/暂停按钮的媒体通知,点击通知可回到播放器页面,通知栏按钮也能直接控制播放状态啦~

内容的提问来源于stack exchange,提问作者user13638878

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 19:17:29