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

Android前台服务中MediaPlayer播放2分钟后停止问题求助

MediaPlayer播放2分钟后停止,低码率MP3文件存在异常

问题描述

我正在实现MediaPlayer,但播放2分钟后就会停止,仿佛未运行在前台服务中。前台服务从Fragment启动,仅需在Fragment存活期间运行。

设备为Android 13,模拟器中运行正常。设置player.isLooping = true时,会循环播放这2分钟内容,说明服务仍存活。

相关代码

前台服务代码

class MediaPlayerForegroundService : Service()  {

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(1, notificationToDisplayServiceInform(), FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)

        lockCpu()

        fileName = intent?.getStringExtra("fileName")

        handler = Looper.myLooper()?.let { Handler(it) }

        player = MediaPlayer().apply {
            setWakeMode(applicationContext, PowerManager.PARTIAL_WAKE_LOCK)
        }

        player!!.setScreenOnWhilePlaying(true)

        val afd: AssetFileDescriptor = applicationContext.assets.openFd(fileName!!)
        player!!.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length);
        afd.close()

        player!!.setOnPreparedListener {
            handler!!.postDelayed(runnableCheck!!, 200)
        }

        player!!.prepareAsync()

        return START_REDELIVER_INTENT
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(
                channelId,
                "Foreground Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            val manager = getSystemService(
                NotificationManager::class.java
            )
            manager.createNotificationChannel(serviceChannel)
        }
    }

    private fun notificationToDisplayServiceInform(): Notification {
        createNotificationChannel()
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            0, notificationIntent, PendingIntent.FLAG_MUTABLE
        )
        return NotificationCompat.Builder(this, channelId)
            .setContentTitle("Simple Foreground Service")
            .setContentText("Explain about the service")
            .setSmallIcon(R.drawable.player_play)
            .setContentIntent(pendingIntent)
            .build()
    }

    private fun lockCpu() {
        wakeLock =
            (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
                newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Movapp::WakeLockFairyTale").apply {
                    acquire()
                }
            }
    }

}

Fragment代码

class PlayerFragment : Fragment() {


    private fun startMediaPlayerService(fileName: String){
        Intent(context, MediaPlayerForegroundService::class.java).also {
            it.putExtra("fileName", fileName)
        }.also {
            context!!.startForegroundService(it)
        }
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
...
....
        startMediaPlayerService("stories/${slug}/${langPair.to.langCode}.mp3")

        return root
    }


    override fun onDestroyView() {
        super.onDestroyView()

        stopMediaPlayerService()

        _binding = null
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cz.movapp.app">

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

    <application
        <service android:name=".MediaPlayerForegroundService"
            android:foregroundServiceType="mediaPlayback"
            android:enabled="true"
            android:exported="false"
            />
    </application>

</manifest>

排查线索

  1. 发现AssetFileDescriptor的处理可能存在问题:afd.length和afd.declaredLength的值均不正确,多个文件出现此情况。
  2. 仅比特率低于96kbps的MP3文件存在2分钟播放限制,OGG文件可正常播放。官方文档显示8-320Kbps的CBR或VBR编码MP3是支持的,怀疑是否为系统Bug?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:40:24