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

Android如何从Notification Player获取歌曲标题、艺术家、专辑等信息

从通知栏媒体播放器(Notification Player)获取歌曲元数据的实现指引

以下为Android平台的完整实现方案:

1. 前置权限申请

要读取系统通知栏的媒体播放信息,首先需要获取用户手动授予的「通知访问权限」:

  • 第一步,在AndroidManifest.xml中注册通知监听服务:
<service
    android:name=".MediaNotificationListenerService"
    android:label="媒体通知监听服务"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>
  • 第二步,在应用启动时检查权限,未授权则引导用户跳转系统设置页授权:
// 检查是否已获取通知监听权限
val isNotificationAccessGranted = Settings.Secure.getString(
    contentResolver,
    "enabled_notification_listeners"
)?.contains(packageName) == true

// 未授权则跳转授权页
if (!isNotificationAccessGranted) {
    startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"))
}

2. 实现监听服务读取媒体数据

继承系统NotificationListenerService类,重写通知发布回调,筛选媒体通知读取对应元数据:

class MediaNotificationListenerService : NotificationListenerService() {
    override fun onNotificationPosted(sbn: StatusBarNotification?) {
        super.onNotificationPosted(sbn)
        sbn?.notification?.extras?.let { extras ->
            // 筛选媒体类通知
            val isMediaNotification = extras.containsKey(Notification.EXTRA_MEDIA_SESSION)
            if (!isMediaNotification) return@let

            // 读取标准歌曲元数据
            val songTitle = extras.getString(Notification.EXTRA_TITLE) ?: "" // 歌曲标题
            val artist = extras.getString(Notification.EXTRA_TEXT) ?: "" // 艺术家名称
            val albumName = extras.getString(Notification.EXTRA_SUB_TEXT) ?: "" // 专辑名称

            // 读取专辑封面Bitmap,可自行保存到本地获取路径
            val albumArtBitmap = extras.getParcelable<Bitmap>(Notification.EXTRA_LARGE_ICON)
            val albumArtLocalPath = saveBitmapToLocal(albumArtBitmap)
        }
    }

    // 示例方法:将Bitmap保存到应用私有目录,返回本地路径
    private fun saveBitmapToLocal(bitmap: Bitmap?): String? {
        bitmap ?: return null
        val targetFile = File(filesDir, "album_art_${System.currentTimeMillis()}.png")
        return runCatching {
            FileOutputStream(targetFile).use { fos ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
            }
            targetFile.absolutePath
        }.getOrNull()
    }
}

3. 注意事项

  • 部分小众音乐应用和自定义ROM可能会修改媒体通知的字段结构,如果读不到标准字段的内容,可以尝试解析通知携带的自定义contentView布局提取对应文本和图片
  • 通知监听服务被系统杀死后,需要重新验证权限绑定状态,建议在应用每次启动时校验服务运行状态
  • Android 13及以上版本不需要额外申请普通通知权限,只要用户授予通知监听权限即可正常读取媒体通知内容

内容的提问来源于stack exchange,提问作者이주현

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:18:03