|
|
|
@ -23,6 +23,7 @@ class AudioRecordingForegroundService : Service() { |
|
|
|
private const val NOTIFICATION_ID = 1001 |
|
|
|
private const val CHANNEL_ID = "audio_recording_channel" |
|
|
|
private const val CHANNEL_NAME = "音频录制服务" |
|
|
|
private const val ACTION_STOP = "com.yunqiinnovation.azure_speech.tools.STOP_SERVICE" |
|
|
|
|
|
|
|
/** |
|
|
|
* 启动前台服务 |
|
|
|
@ -44,8 +45,9 @@ class AudioRecordingForegroundService : Service() { |
|
|
|
*/ |
|
|
|
fun stopService(context: Context) { |
|
|
|
val intent = Intent(context, AudioRecordingForegroundService::class.java) |
|
|
|
context.stopService(intent) |
|
|
|
Log.d(TAG, "音频录制前台服务已停止") |
|
|
|
intent.action = ACTION_STOP |
|
|
|
context.startService(intent) |
|
|
|
Log.d(TAG, "发送停止音频录制前台服务指令") |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
@ -56,12 +58,21 @@ class AudioRecordingForegroundService : Service() { |
|
|
|
} |
|
|
|
|
|
|
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { |
|
|
|
Log.d(TAG, "AudioRecordingForegroundService onStartCommand") |
|
|
|
Log.d(TAG, "AudioRecordingForegroundService onStartCommand action=${intent?.action}") |
|
|
|
|
|
|
|
// 创建前台通知 |
|
|
|
val notification = createNotification() |
|
|
|
// 必须立即调用 startForeground 以满足 Android 8.0+ 的要求 |
|
|
|
startForeground(NOTIFICATION_ID, notification) |
|
|
|
|
|
|
|
// 检查是否是停止指令 |
|
|
|
if (intent?.action == ACTION_STOP) { |
|
|
|
Log.d(TAG, "收到停止指令,停止服务") |
|
|
|
stopForeground(true) |
|
|
|
stopSelf() |
|
|
|
return START_NOT_STICKY |
|
|
|
} |
|
|
|
|
|
|
|
// 返回START_STICKY确保服务被系统杀死后会重启 |
|
|
|
return START_STICKY |
|
|
|
} |
|
|
|
|