0

Я написал Service, установил Foreground, чтобы не уничтожался системой.

C помощью BroadcastReceiver отлавливаю intent от service и передаю получившиеся значение в textView.

При закрытий Activity, уничтожается и Service.

Почему так происходит?

Service

class RecordingService : Service() {

    private val TAG = "RecordingService"
    override fun onCreate() {
        super.onCreate()    
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when(intent?.action){
            RecorderState.PLAY.name -> {
                samplingRate = intent.getIntExtra("samplingRate", 41000)
                outputFile = intent.getStringExtra("outputFile")
                startRecording()
            }

            RecorderState.PAUSE.name -> {
                pauseRecording()
            }
            RecorderState.RESUME.name -> {
                resumeRecording()
            }
            RecorderState.STOP.name -> {
                stopRecording()
            }
        }
        return START_NOT_STICKY
    }

    override fun onDestroy() {
        if(mediaRecorder != null){
            stopRecording()
        }
        super.onDestroy()

    }


    private fun startRecording(){
        ......
        startForeground(1, createNotification())
        Log.d(TAG, "Start")
    }

    private fun createNotification(): Notification {
        var builder : NotificationCompat.Builder? = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = createNotificationChannel("my_service", "My Background Service")
            builder = NotificationCompat.Builder(this, channelId)
            .setContentTitle("Запись звука....")
            .setContentText(timerFormat.format(recordingTimeMillies))
            .setOngoing(true)
        }
        else{
            builder = NotificationCompat.Builder(this)
                .setContentTitle("Запись звука....")
                .setContentText(timerFormat.format(recordingTimeMillies))
                .setOngoing(true)
        }

        builder.setContentIntent(
            PendingIntent.getActivities(
                applicationContext, 0,
                arrayOf(Intent(applicationContext, RecorderFragment::class.java)), 0
            )
        )

        val stopIntent = Intent(applicationContext, RecordingService::class.java)
        stopIntent.action = "STOP_RECORDING"
        builder.addAction(
            R.drawable.ic_stop_black_24dp, "Stop", PendingIntent.getService(
                applicationContext, 0, stopIntent, 0
            )
        )
        return builder.build()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(channelId: String, channelName: String): String{
        val chan = NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_NONE)
        chan.lightColor = Color.BLUE
        chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
        val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        service.createNotificationChannel(chan)
        return channelId
    }

}

Fragment

class RecorderFragment : Fragment(){

    companion object{
        val TIME_CHANGE = "ru.ddstudio.voicerecording.ui.recorder.TIME_CHANGE"
    }

    private lateinit var viewModel: RecorderViewModel
    @Inject
    lateinit var viewModelFactory : MainViewModelFactory


    private lateinit var brReceiver : BroadcastReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AppDelegate.appComponent.inject(this)
        initViewModel()
        brReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent) {
                if (intent.action == TIME_CHANGE) {
                    viewModel.recorderTimeChanged(intent.getLongExtra("timeRecording", 0))
                }
            }
        }
        val intentFilter = IntentFilter()
        intentFilter.addAction(TIME_CHANGE)
        context!!.registerReceiver(brReceiver, intentFilter)


    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fr_add_voice, container, false)
        root.btn_save_voice.setOnClickListener{viewModel.stopRecording()}
        root.btn_delete_voice.setOnClickListener{viewModel.deleteRecord()}
        root.fab.setOnClickListener{viewModel.startRecording()}



        return root
    }

    private fun initViewModel(){
        viewModel = ViewModelProviders.of(this, viewModelFactory).get(RecorderViewModel::class.java)
        viewModel.getTime().observe(this, Observer { updateTime(it)})
//        viewModel.getTime().observe(this, Observer {updateTime(it)})
        viewModel.getRecorderState().observe(this, Observer { updateRecorderState(it) })
//        viewModel.getOutputFileName().observe(this, Observer { updateOutputFileName(it) })
    }

    private fun updateOutputFileName(outputFileName: String) {
        et_filename.setText(outputFileName)
    }

    private fun updateTime(time : Long){
        tv_time.text = timeInString(time)
    }




    private fun updateRecorderState(recorderState : RecorderState){
        val intent = Intent(context, RecordingService::class.java)
        when(recorderState){
            RecorderState.PLAY -> {
                if(isPermissionGranted(Manifest.permission.RECORD_AUDIO)&& isPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //PAUSE
                        } else {
                        //STOP

                    val outputFileName = if(et_filename.text.toString().trim() != "") {
                        val date = DateTime.now()
                        Log.d("Время", date.toString())
                    val outputFile = "$direction/${outputFileName}"
                    intent.putExtra("outputFile", outputFile)
                    intent.action = RecorderState.PLAY.name
                    intent.putExtra("samplingRate", Integer.parseInt(sharedPreferences.getString("samplingRateKey", "50000").toString()))
                    context?.startService(intent)

                }
            RecorderState.PAUSE -> {
                intent.action = RecorderState.PAUSE.name
                context?.startService(intent)
            }
            RecorderState.RESUME -> {
                intent.action = RecorderState.RESUME.name
                context?.startService(intent)
            }
            RecorderState.STOP -> {

                intent.action = RecorderState.STOP.name              
                context?.startService(intent)
            }
        }
    }

override fun onDestroy() {
        context?.unregisterReceiver(brReceiver)
        super.onDestroy()
    }

Manifest:

<service
            android:name=".services.RecordingService"
            android:enabled="true"
            android:exported="false"></service>
2
  • Что-то не вижу код для запуска сервиса 21 ноя 2019 в 12:57
  • @VitalyTomashevsky метод private fun updateRecorderState(), конец ветки RecorderState.PLAY
    – danilshik
    21 ноя 2019 в 12:59

1 ответ 1

1

Без кода сложно что то сказать, но попробую погадать на кофейной гуще:

  1. Если вы используете Binder для взаимодействия с сервисом, то скорее всего по окончанию его работы он закроет сервис.
  2. метод onStartCommand в сервисе должен возвращать START_STICKY
  3. Возможно, в активити есть метод который вызывает остановку сервиса stopService(Intent) и он срабатывает при onDestroy.
  4. Попробуйте выделить сервис в отдельный процесс. Для этого добавьте в манифесте android:process=":имявашегоотдельногопроцессадлясервиса"
2
  • добавил код. Только я не понимаю, для чего START_STICKY, это же всего лишь флаг, который показывает, воскрешать ли сервис после убийства. Мне этого не требуется (так как диктофон)
    – danilshik
    21 ноя 2019 в 12:34
  • как я понял, только 4 пункт подходит мне, как этот процесс для него создать?
    – danilshik
    21 ноя 2019 в 18:52

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.