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

Android 12及以上版本Notification功能失效,求修复方案

Android 12+ 音乐应用通知功能修复方案

核心问题分析

你的代码在Android 12及以上版本失效,主要是因为两项系统强制变更:

  1. PendingIntent必须指定可变性标志:API 31开始要求创建PendingIntent时显式设置FLAG_IMMUTABLE或FLAG_MUTABLE,旧代码中用0作为flags会直接抛出异常。
  2. 后台服务启动限制:Android 12禁止通过PendingIntent.getService()启动后台服务,必须改用前台服务专用API或通过广播中转逻辑。

具体修复步骤

1. 修复PendingIntent的标志位

所有PendingIntent创建时都需要添加可变性标志,同时保留FLAG_UPDATE_CURRENT确保intent内容更新生效:

// 启动Activity的PendingIntent
during = PendingIntent.getActivity(this, 0, sendNotify, 
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

2. 修复播放按钮的PendingIntent

根据你的Notify服务类型选择对应方案:

方案A:如果Notify是前台服务(音乐应用推荐)

改用getForegroundService()创建PendingIntent,这是Android 12+启动前台服务的标准方式:

Intent sendPlay = new Intent(this, Notify.class);
sendPlay.setAction(Fixed.ACTION.PLAY_ACT);
PendingIntent pendingPlayIntent = PendingIntent.getForegroundService(this, 0,
        sendPlay, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
方案B:如果Notify是后台服务(不推荐音乐应用使用)

通过BroadcastReceiver中转逻辑,避免直接启动后台服务:

  • 新建广播接收器类:
public class PlayControlReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Fixed.ACTION.PLAY_ACT.equals(intent.getAction())) {
            Intent serviceIntent = new Intent(context, Notify.class);
            // 适配不同版本的服务启动方式
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(serviceIntent);
            } else {
                context.startService(serviceIntent);
            }
        }
    }
}
  • 在AndroidManifest.xml中注册接收器:
<receiver
    android:name=".PlayControlReceiver"
    android:exported="false">
    <intent-filter>
        <action android:name="your.package.name.PLAY_ACT"/>
    </intent-filter>
</receiver>
  • 修改PendingIntent创建代码:
Intent sendPlay = new Intent(this, PlayControlReceiver.class);
sendPlay.setAction(Fixed.ACTION.PLAY_ACT);
PendingIntent pendingPlayIntent = PendingIntent.getBroadcast(this, 0,
        sendPlay, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

3. 确保前台服务和通知渠道合规

  • 音乐服务必须是前台服务,启动后需立即显示通知(Android 8.0+要求)。
  • 确认已创建通知渠道(Android 8.0+强制要求):
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(
            "music_playback_channel",
            "音乐播放通知",
            NotificationManager.IMPORTANCE_LOW
    );
    NotificationManager notificationManager = getSystemService(NotificationManager.class);
    notificationManager.createNotificationChannel(channel);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 21:45:06