You need to enable JavaScript to run this app. 安卓音频应用:点击RecyclerView项同步启动前台通知的实现教程
优惠活动
大模型
产品
解决方案
定价
更多

安卓音频应用:点击RecyclerView项同步启动前台通知的实现教程

安卓音频应用 点击列表项同步启动前台播放通知 实现方案

所有代码可直接拷贝复用,适配安卓8.0到安卓14的全版本,新手不需要额外理解复杂原理。

前置必填配置(漏了通知会完全不显示)

在项目的AndroidManifest.xml文件中完成以下配置:

  • 添加对应权限:
    <!-- 安卓9.0+ 前台服务权限 -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <!-- 安卓14.0+ 音频类前台服务强制权限 -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
    <!-- 安卓13.0+ 通知弹出权限 -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    
  • 注册前台音频服务组件:
    <application
        ...>
        <!-- 其他原有组件保持不动 -->
        <service
            android:name=".AudioPlaybackService"
            android:foregroundServiceType="mediaPlayback"
            android:exported="false"/>
    </application>
    

第一步:创建前台通知绑定的音频服务类

直接在项目根目录新建AudioPlaybackService.java,把以下代码完整拷贝进去:

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

public class AudioPlaybackService extends Service {
    // 固定常量,不需要修改
    private static final String CHANNEL_ID = "audio_play_channel";
    private static final int NOTIFICATION_ID = 10086;
    public static final String EXTRA_SONG_NAME = "current_playing_song";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 从启动意图里拿当前播放的歌曲名,显示在通知上
        String songName = intent.getStringExtra(EXTRA_SONG_NAME);
        // 创建通知渠道(安卓8.0+必须,没有渠道通知不会弹出)
        createNotificationChannel();

        // 设置点击通知时跳转到Player页面的意图
        Intent jumpToPlayerIntent = new Intent(this, Player.class);
        PendingIntent contentPendingIntent = PendingIntent.getActivity(
                this,
                0,
                jumpToPlayerIntent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );

        // 构建通知内容
        Notification playNotification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_music) // 换成你自己应用的小图标资源ID
                .setContentTitle("正在播放音频")
                .setContentText(songName)
                .setContentIntent(contentPendingIntent)
                .setOngoing(true) // 播放期间通知不允许被用户手动划掉
                .build();

        // 把当前服务转为前台服务,绑定通知
        startForeground(NOTIFICATION_ID, playNotification);
        return START_NOT_STICKY;
    }

    // 内部方法:创建系统要求的通知渠道
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "音频播放通知",
                    NotificationManager.IMPORTANCE_LOW // 低优先级,不会发出提示音打扰用户
            );
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    // 服务销毁时移除通知
    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(STOP_FOREGROUND_REMOVE);
    }
}

第二步:修改Player Activity 的播放逻辑,同步拉起通知

不需要改动RecyclerView的Adapter代码,所有通知联动逻辑统一在Player页面实现,避免不同入口逻辑不一致。

  1. 在Player类的成员变量区域加一个权限请求常量:
    // 通知权限请求码,自定义即可
    private static final int REQUEST_NOTIFICATION_PERMISSION = 1001;
    
  2. 找到你原来写的getIntentMethod()方法,在mMediaplayer.start()逻辑的最后,加上启动前台服务的代码:
    private void getIntentMethod() {
        position= getIntent().getIntExtra("position",-1);
        macam=cardalbums;
        macam=malbie;
    
        if(macam!=null ){
            playpausebtn.setImageResource(R.drawable.ic_baseline_pause_24);
            currentItem = cardalbums.get(position);
            currentItem = malbie.get(position);
        }
        if(mMediaplayer!=null){
            mMediaplayer.stop();
            mMediaplayer.release();
            mMediaplayer= MediaPlayer.create(getApplicationContext(),currentItem.getAudio());
            mMediaplayer.start();
    
        }else{
            mMediaplayer= MediaPlayer.create(getApplicationContext(),currentItem.getAudio());
            mMediaplayer.start();
        }
    
        seekBar.setMax(mMediaplayer.getDuration()/ 1000);
    
        // ———— 以下为新增的前台通知启动逻辑 ————
        // 安卓13+ 动态申请通知权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS)
                    != getPackageManager().PERMISSION_GRANTED) {
                requestPermissions(
                        new String[]{android.Manifest.permission.POST_NOTIFICATIONS},
                        REQUEST_NOTIFICATION_PERMISSION
                );
            }
        }
        // 启动前台音频服务
        Intent playServiceIntent = new Intent(this, AudioPlaybackService.class);
        playServiceIntent.putExtra(AudioPlaybackService.EXTRA_SONG_NAME, currentItem.getSurah());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(playServiceIntent);
        } else {
            startService(playServiceIntent);
        }
    }
    
  3. 重写Player的onDestroy()方法,页面退出时同步关掉前台服务,避免通知残留:
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 页面销毁时停止前台服务
        stopService(new Intent(this, AudioPlaybackService.class));
    }
    

补充提醒

  • 通知的小图标请使用透明背景的矢量图标,不要用带彩色块的位图,否则安卓高版本会把图标显示成纯白色方块
  • 你原有代码中开子线程给按钮设置点击事件的写法不符合安卓规范,所有UI控件的监听必须在主线程设置,后续维护时可以把那几个开线程设置按钮监听的代码删掉,直接在initViews()方法里设置点击事件,避免内存泄漏
  • RecyclerView的Adapter代码完全不需要改动,原有的点击跳Player的逻辑已经可以触发通知拉起,不需要重复写通知代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 06:15:10