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

Android后台播放音频1分钟后自动停止,求代码优化解决方法

Android后台音频持续播放问题解决方案

你的核心问题是Android 8.0+ 对后台服务的限制:普通Service在应用进入后台后,系统会在短时间内(通常1分钟)将其回收,必须改用前台服务才能保持长期运行。结合你的代码,需要做以下修改:

1. 改造Service为前台服务并添加通知

在TheService.kt中创建前台通知,让系统识别这是需要持续运行的音频服务:

package me.soft.myapp

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.Build
import android.os.IBinder
import android.provider.Settings
import androidx.core.app.NotificationCompat

class TheService: Service() {
    private lateinit var audioPlayer: MediaPlayer
    private val CHANNEL_ID = "AudioPlaybackChannel"
    private val NOTIFICATION_ID = 1001

    override fun onCreate() {
        super.onCreate()
        // Android 8.0+ 必须创建通知渠道
        createNotificationChannel()
    }

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

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 直接初始化MediaPlayer,无需额外线程
        audioPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI)
        audioPlayer.isLooping = true
        audioPlayer.start()

        // 构建前台通知
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("音频播放中")
            .setContentText("后台持续运行")
            .setSmallIcon(android.R.drawable.ic_media_play)
            .build()

        // 启动前台服务,绑定通知
        startForeground(NOTIFICATION_ID, notification)

        // 服务被杀死后尝试重启,适配播放场景
        return START_STICKY
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "音频播放通道",
                NotificationManager.IMPORTANCE_LOW // 低优先级不打扰用户
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 正确释放MediaPlayer资源,避免内存泄漏
        if (::audioPlayer.isInitialized) {
            audioPlayer.stop()
            audioPlayer.release()
        }
    }
}

2. 更新AndroidManifest.xml权限与服务配置

添加前台服务权限,并指定服务类型为媒体播放(Android 12+ 强制要求):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="me.soft.myapp">

    <!-- 添加前台服务权限 -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="myapp"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ServiceTry"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- 声明服务为前台服务,指定媒体播放类型 -->
        <service 
            android:name=".TheService"
            android:foregroundServiceType="mediaPlayback" />
    </application>

</manifest>

关键修改说明

  • 前台服务:通过startForeground绑定通知,系统会将服务视为“用户可见”任务,不会轻易回收。
  • 通知渠道:Android 8.0+ 强制要求,否则通知无法显示,前台服务启动失败。
  • MediaPlayer优化:移除不必要的子线程,在onDestroy中释放资源,避免内存泄漏。
  • 返回值调整:START_STICKY让服务被意外杀死后自动重启,更适合音频播放场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:18:14