【问题标题】:how to restart a job in coroutine?如何在协程中重新启动作业?
【发布时间】:2020-12-02 15:16:27
【问题描述】:

我使用协程使用 audiorecord 进行录制。在我使用 start 和 stop 并开始工作后,工作不会开始任何事情。有没有办法重新开始工作?我想开始->停止->开始,因为它正在录制。这是我的代码。起初,我的应用程序开始录制,当我单击录制按钮时,作业被取消。但是当我再次单击录制按钮时,作业没有开始。

onCreate

 scope = CoroutineScope(Dispatchers.Default)
        job =scope.launch {
            val readData = ByteArray(mBufferSize)
            mFilePath = getExternalTempFileDirectory(this@AudioRecorderActivity)+"/audiorecord.pcm"
            var fos: FileOutputStream? = null
            try {
                fos = FileOutputStream(mFilePath)
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }
            while (isRecording) {
                val ret = mAudioRecord!!.read(readData, 0, mBufferSize)
                Log.d(TAG, "read bytes is $ret")
                try {
                    fos!!.write(readData, 0, mBufferSize)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            mAudioRecord!!.stop()
            mAudioRecord!!.release()
            mAudioRecord = null
            try {
                fos?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

录音功能

   fun onRecord() {
        if (isRecording == true) {
            isRecording = false
            job.cancel()
            binding.recordStartButton!!.text = "Record"

        } else {
            isRecording = true
            job.start()
            binding.recordStartButton!!.text = "Stop"
            if (mAudioRecord == null) {
                mAudioRecord = AudioRecord(mAudioSource, mSampleRate, mChannelCount, mAudioFormat, mBufferSize)
                mAudioRecord!!.startRecording()
            }

        }
    }

【问题讨论】:

  • 作业一旦取消就无法恢复,您必须重新开始。您还应该改用SupervisorScope,否则取消会“向上”传播,这会导致托管已取消作业的范围也被取消。

标签: android


【解决方案1】:

在 Kotlin Coroutines 中,取消的作业无法重新启动。您需要创建一个新工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 2014-11-15
    相关资源
    最近更新 更多