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)没有帮助。
| 归档时间: |
|
| 查看次数: |
601 次 |
| 最近记录: |