package com.example.sonya

import android.Manifest
import android.animation.ObjectAnimator
import android.content.SharedPreferences
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import java.io.InputStream
import java.net.ServerSocket
import java.net.Socket
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    private val sampleRate = 44100
    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var recordButton: Button
    private var animator: ObjectAnimator? = null
    private var audioServerSocket: ServerSocket? = null

    companion object {
        const val PREFS_NAME = "AppPrefs"
        const val KEY_IS_RECORDING = "IsRecording"
        const val KEY_IS_PLAYING_AUDIO = "IsPlayingAudio"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
        recordButton = findViewById(R.id.recordButton)

        // Запрос разрешений
        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.INTERNET), 1)

        // Восстановление состояния
        restoreState()

        recordButton.setOnClickListener {
            if (sharedPreferences.getBoolean(KEY_IS_RECORDING, false)) {
                stopRecording()
            } else {
                startRecording()
            }
        }

        startAudioPlayback()
        startSocketServer()
    }

    private fun startSocketServer() {
        thread {
            try {
                val serverSocket = ServerSocket(51411)
                while (true) {
                    val clientSocket: Socket = serverSocket.accept()
                    val inputStream: InputStream = clientSocket.getInputStream()
                    val buffer = ByteArray(1024)
                    val read = inputStream.read(buffer)
                    val message = String(buffer, 0, read)

                    when (message) {
                        "ACTIVATED" -> {
                            runOnUiThread {
                                onActivationReceived()
                            }
                        }
                        "DEACTIVATED" -> {
                            runOnUiThread {
                                onDeactivationReceived()
                            }
                        }
                    }

                    inputStream.close()
                    clientSocket.close()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun onActivationReceived() {
        recordButton.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#FFCC0000"))
    }

    private fun onDeactivationReceived() {
        recordButton.backgroundTintList = null
    }

    private fun startAudioPlayback() {
        if (audioServerSocket == null) {
            thread {
                try {
                    audioServerSocket = ServerSocket(51412)
                    while (true) {
                        val clientSocket: Socket = audioServerSocket!!.accept()
                        handleAudioClient(clientSocket)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    private fun handleAudioClient(clientSocket: Socket) {
        var inputStream: InputStream? = null
        try {
            inputStream = clientSocket.getInputStream()

            val bufferSize = AudioTrack.getMinBufferSize(
                48000,
                AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT
            )
            val audioTrack = AudioTrack(
                AudioManager.STREAM_MUSIC,
                48000,
                AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                bufferSize,
                AudioTrack.MODE_STREAM
            )
            audioTrack.play()

            // Изменяем состояние
            AudioService.isPlayingAudio = true
            sharedPreferences.edit().putBoolean(KEY_IS_PLAYING_AUDIO, true).apply()

            val buffer = ByteArray(bufferSize)
            var read: Int

            while (inputStream.read(buffer).also { read = it } != -1) {
                audioTrack.write(buffer, 0, read)
            }

            audioTrack.stop()
            audioTrack.release()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                inputStream?.close()
                clientSocket.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            AudioService.isPlayingAudio = false
            sharedPreferences.edit().putBoolean(KEY_IS_PLAYING_AUDIO, false).apply()
        }
    }

    private fun startRecording() {
        sharedPreferences.edit().putBoolean(KEY_IS_RECORDING, true).apply()
        animateButton(true)

        // Запускаем сервис
        val serviceIntent = Intent(this, AudioService::class.java)
        startService(serviceIntent)
    }

    private fun stopRecording() {
        sharedPreferences.edit().putBoolean(KEY_IS_RECORDING, false).apply()
        animateButton(false)

        // Останавливаем сервис
        val serviceIntent = Intent(this, AudioService::class.java)
        stopService(serviceIntent)
    }

    private fun animateButton(isRecording: Boolean) {
        if (isRecording) {
            animator = ObjectAnimator.ofFloat(recordButton, "scaleX", 1.0f, 1.2f)
            animator?.duration = 300
            animator?.repeatCount = ObjectAnimator.INFINITE
            animator?.repeatMode = ObjectAnimator.REVERSE
            animator?.start()
        } else {
            animator?.cancel()
            recordButton.scaleX = 1.0f
        }
    }

    private fun restoreState() {
        if (sharedPreferences.getBoolean(KEY_IS_RECORDING, false)) {
            startRecording()
        }
        if (sharedPreferences.getBoolean(KEY_IS_PLAYING_AUDIO, false)) {
            onActivationReceived()
        }
    }
}

package com.example.sonya

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi
import java.io.OutputStream
import java.net.Socket

class AudioService : Service() {

    private val sampleRate = 44100
    private var isRecording = false
    private lateinit var audioRecord: AudioRecord

    companion object {
        var isPlayingAudio = false // Общая переменная для отслеживания состояния воспроизведения
    }

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

    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("ForegroundServiceType")
    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        startForeground(1, createNotification())
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startRecording()
        return START_STICKY
    }

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

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotification(): Notification {
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_IMMUTABLE)

        return Notification.Builder(this, "AudioServiceChannel")
            .setContentTitle("Audio Service")
            .setContentText("Recording audio in background")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentIntent(pendingIntent)
            .build()
    }

    @SuppressLint("MissingPermission")
    private fun startRecording() {
        isRecording = true
        Thread {
            val bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
            audioRecord = AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize)
            audioRecord.startRecording()

            try {
                val socket = Socket("192.168.0.105", 6543)
                val outputStream: OutputStream = socket.getOutputStream()
                val buffer = ByteArray(bufferSize)

                while (isRecording) {
                    // Приостанавливаем запись, если идет воспроизведение аудио
                    if (isPlayingAudio) {
                        Log.d("AudioService", "Recording paused: Audio is playing")
                        Thread.sleep(100) // Ждем 100 мс перед следующей проверкой
                        continue
                    }

                    val read = audioRecord.read(buffer, 0, buffer.size)
                    outputStream.write(buffer, 0, read)
                }

                outputStream.close()
                socket.close()
            } catch (e: Exception) {
                Log.e("AudioService", "Error recording audio", e)
            } finally {
                audioRecord.stop()
                audioRecord.release()
            }
        }.start()
    }

    private fun stopRecording() {
        isRecording = false
    }

    override fun onDestroy() {
        super.onDestroy()
        stopRecording()
    }
}

При переходе из фонового режима обратно в приложение почему то не обрабатываются package com.example.sonya

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi
import java.io.OutputStream
import java.net.Socket

class AudioService : Service() {

    private val sampleRate = 44100
    private var isRecording = false
    private lateinit var audioRecord: AudioRecord

    companion object {
        var isPlayingAudio = false // Общая переменная для отслеживания состояния воспроизведения
    }

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

    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("ForegroundServiceType")
    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        startForeground(1, createNotification())
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startRecording()
        return START_STICKY
    }

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

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotification(): Notification {
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_IMMUTABLE)

        return Notification.Builder(this, "AudioServiceChannel")
            .setContentTitle("Audio Service")
            .setContentText("Recording audio in background")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentIntent(pendingIntent)
            .build()
    }

    @SuppressLint("MissingPermission")
    private fun startRecording() {
        isRecording = true
        Thread {
            val bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
            audioRecord = AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize)
            audioRecord.startRecording()

            try {
                val socket = Socket("192.168.0.105", 6543)
                val outputStream: OutputStream = socket.getOutputStream()
                val buffer = ByteArray(bufferSize)

                while (isRecording) {
                    // Приостанавливаем запись, если идет воспроизведение аудио
                    if (isPlayingAudio) {
                        Log.d("AudioService", "Recording paused: Audio is playing")
                        Thread.sleep(100) // Ждем 100 мс перед следующей проверкой
                        continue
                    }

                    val read = audioRecord.read(buffer, 0, buffer.size)
                    outputStream.write(buffer, 0, read)
                }

                outputStream.close()
                socket.close()
            } catch (e: Exception) {
                Log.e("AudioService", "Error recording audio", e)
            } finally {
                audioRecord.stop()
                audioRecord.release()
            }
        }.start()
    }

    private fun stopRecording() {
        isRecording = false
    }

    override fun onDestroy() {
        super.onDestroy()
        stopRecording()
    }
}

и следовательно не меняется цвет кнопки на красный и обратно