麦克风前台服务几乎总是被某些操作系统杀死

Sea*_*ici 7 android microphone foreground-service

我根本不明白为什么我的手机会杀死我的前台服务。

相关代码

在 AndroidManifest 中:

    <service
        android:name=".recorder.RecorderService"
        android:exported="false"
        android:process=":Recorder"
        android:foregroundServiceType="microphone">
    </service>
Run Code Online (Sandbox Code Playgroud)

在我的服务启动器中

     ContextCompat.startForegroundService(application, Intent(application, RecorderService::class.java))
Run Code Online (Sandbox Code Playgroud)

实际服务里面

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO)

    val notification = buildRecordingNotification()
    startServiceWithNotification(notification)

    recordingJob = recordSounds.executeCancellable(Unit, serviceScope)

    return START_STICKY
}

private fun buildRecordingNotification(): Notification {
    val channelId = buildNotificationChannelId()
    val builder = NotificationCompat.Builder(this, channelId)
    return builder
        .setSmallIcon(R.drawable.ic_stat_notify)
        .setContentTitle("Recording...")
        .setWhen(0)
        .setChannelId(channelId)
        .build()
}

private fun buildNotificationChannelId() =
    NotificationChannelHelper.createChannel(this, NotificationChannelHelper.NOTIF_ID_RECORDER, NotificationManagerCompat.IMPORTANCE_LOW)

private fun startServiceWithNotification(notification: Notification) =
    try {
        startForeground(NOTIFICATION_ID, notification)
    } catch (e: Exception) {
        Log.e("RecorderService", "Failed to startForeground", e)
    }
Run Code Online (Sandbox Code Playgroud)

在我的录音工作中

private suspend fun startRecorder() {
    audioRecord = withContext(Dispatchers.Main) {
        CustomAudioRecord().also { ar ->
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO)
            ar.startRecording()
            recordingSessionId = UUID.randomUUID().toString()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题

在 OnePlus 手机上,当屏幕关闭并将应用程序置于后台时(最简单的重现方法),前台服务会在大约 30 分钟后终止(应用程序也是如此)

我尝试过的

  • 我尝试创建一个轻量级进程来托管服务,在其中仅注入服务运行所需的依赖项。整个进程占用大约 120mb 的内存,而主进程运行时则占用近 700mb。

  • 我检查了 dumpsys 日志并在我的服务上得到了以下读数:

      Proc #25: prcp   F/S/FGS  --M  t: 0 22173:***Recorder/u0a714 (fg-service)
    
    Run Code Online (Sandbox Code Playgroud)

看起来它是一个正确创建的前台服务。

  • 我尝试使用android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO)

没有帮助。

  • 我检查了唤醒锁(尝试明确使用另一个唤醒锁),并且麦克风输入唤醒锁在我的服务期间处于活动状态。

一些注意事项

  • 我们还有另一个用于媒体播放的前台服务,它通常不会在 OnePlus 手机上被杀死。它是用同样的方式构建的。
  • 在某些设备上,该服务全天整夜运行都没有问题。