0

I have an IntentService running in my app. I want to stop when user presses a cancel button, but onHandleIntent keeps running, even when onDestroy (IntentService) was called.

I tried stopSelf() in the middle of execution, stopSelf(int) and stopService(intent), but doesn't work.

class DownloadIntentService : IntentService("DownloadIntentService") {

    val TAG: String = "DownloadIntentService"

    val AVAILABLE_QUALITIES: Array<Int> = Array(5){240; 360; 480; 720; 1080}

    // TODO Configurations
    val PREFERED_LANGUAGE = "esLA"
    val PREFERED_QUALITY = AVAILABLE_QUALITIES[0]

    @Inject
    lateinit var getVilosDataInteractor: GetVilosInteractor

    @Inject
    lateinit var getM3U8Interactor: GetM3U8Interactor

    @Inject
    lateinit var downloadDataSource: DownloadsRoomDataSource

    companion object {
        var startedId: Int = 0
    }

    override fun onCreate() {
        super.onCreate()
        (application as CrunchApplication).component.inject(this)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "onStartComand ${startId}")

        startedId = startId

        super.onStartCommand(intent, flags, startId)
        return Service.START_NOT_STICKY
    }

    override fun onHandleIntent(intent: Intent?) {
        Log.d(TAG, "starting download service")

        val download = downloadDataSource.getDownloadById(intent?.getLongExtra(MEDIA_ID_EXTRA, 0) ?: 0)

        Log.d(TAG, "A new download was found: ${download.id} ${download.serieName} ${download.collectionName} ${download.episodeName}")

        val vilosResponse = getVilosDataInteractor(download.episodeUrl)

        val stream: StreamData? = vilosResponse.streams.filter {
            it.hardsubLang?.equals(PREFERED_LANGUAGE) ?: false
        }.getOrNull(0)

        if(stream == null) {
            Log.d(TAG, "Stream not found with prefered language ($PREFERED_LANGUAGE)")
            return
        }

        Log.d(TAG, "Best stream option: " + stream.url)
        val m3u8Response = getM3U8Interactor(stream.url)

        val m3u8Data: M3U8Data? = m3u8Response.playlist.filter { it.height == PREFERED_QUALITY }[0]

        if(m3u8Data == null) {
            Log.d("M3U8","Resolution ${PREFERED_QUALITY}p not found")
            return
        }

        Log.d(TAG, m3u8Data.url)

        val root = Environment.getExternalStorageDirectory().toString()
        val myDir = File(root + "/episodes/");
        if (!myDir.exists()) {
            myDir.mkdirs()
        }

        val output = myDir.getAbsolutePath() + "EPISODENAME.mp4";
        val cmd = "-y -i ${m3u8Data.url} ${output}"

        when (val result: Int = FFmpeg.execute(cmd)) {
            Config.RETURN_CODE_SUCCESS -> Log.d(TAG, "Success")
            Config.RETURN_CODE_CANCEL -> Log.d(TAG, "Cancel")
            else -> Log.d(TAG, "Default: $result")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy")
    }
}

I try to stop from a Fragment

val intent = Intent(requireContext(), DownloadIntentService::class.java)
requireContext().stopService(intent)

Thanks in advance

pablete
  • 101
  • 2
  • Does this answer your question? [How to stop intentservice in android?](https://stackoverflow.com/questions/8709989/how-to-stop-intentservice-in-android) – Vahid Apr 03 '20 at 04:36
  • I already tried stopSelf, but didn't work. I know that IntentService is made to stop itself when the job is done, but I really need to cancel when the user presses the button. Maybe I have to do another implementation, another class to do the job or something else – pablete Apr 03 '20 at 04:45
  • if you need to stop service manually you should use Service instead of IntentService – Vahid Apr 03 '20 at 04:46

1 Answers1

0

Basically you can not. OnHandleIntent run on worker thread. To stop it you have to do same thing which one can do with any another Thread i.e. have a boolean flag check inside onHandleIntent and before doing operation check of this flag is true. Now when you want to cancel update the flag to false.

It also depends on what you are doing. IF something is already in process tat will keep on running. Not you have to have state machine to make it stop.

TheGraduateGuy
  • 1,450
  • 1
  • 13
  • 35