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

Android API 34音频播放通知不显示问题求助

Android 14(API 34)音频前台服务通知不显示问题排查与解决

API 34 专属限制排查

  • 强制指定前台服务类型:API 34 要求所有前台服务必须在清单和启动时声明对应类型,音频服务需指定mediaPlayback。
    检查AndroidManifest.xml的服务配置:

    <service
        android:name=".AudioService"
        android:foregroundServiceType="mediaPlayback"
        android:exported="false">
    </service>
    

    启动前台服务时必须传入类型参数(API34新增,不传会静默失败,这也是你Logcat无报错的核心原因):

    startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)
    
  • 通知渠道合规性:API34对通知渠道可见性要求更严,确保媒体通知渠道优先级为IMPORTANCE_DEFAULT或更高:

    val channel = NotificationChannel(
        CHANNEL_ID,
        "音频播放控制",
        NotificationManager.IMPORTANCE_DEFAULT
    ).apply {
        description = "显示音频播放状态及停止按钮"
        setShowBadge(false)
    }
    notificationManager.createNotificationChannel(channel)
    

代码逻辑修正

  • 启动时机与PendingIntent配置:确保音频播放前调用startForeground(),停止按钮的PendingIntent需绑定服务停止逻辑,且API33+必须指定FLAG_IMMUTABLE:

    val stopIntent = Intent(this, AudioService::class.java).apply {
        action = "ACTION_STOP_AUDIO"
    }
    val stopPendingIntent = PendingIntent.getService(
        this,
        0,
        stopIntent,
        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )
    // 将该PendingIntent添加到通知的Action按钮中
    
  • 服务收尾逻辑:音频停止时需移除通知并终止服务:

    fun stopAudioPlayback() {
        mediaPlayer?.run {
            stop()
            release()
        }
        stopForeground(Service.STOP_FOREGROUND_REMOVE)
        stopSelf()
    }
    

权限验证

  • API33+需申请POST_NOTIFICATIONS权限,启动服务前先检查并请求:
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
            != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_NOTIFICATION_PERM)
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:03:13