如何在Android上停止IntentService



我的应用程序中运行了IntentService。我想在用户按下取消按钮时停止,但onHandleIntent仍在运行,即使调用了onDestroy(IntentService(。

我在执行过程中尝试了stopSelf((、stopSelve(int(和stopService(intent(,但都不起作用。

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")
}
}

我试图从碎片停止

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

提前感谢

基本上你不能。在工作线程上运行OnHandleIntent。要停止它,您必须做与其他线程相同的事情,即在onHandleIntent中检查布尔标志,并在执行操作之前检查该标志是否为true。现在,当您想取消时,请将标志更新为false。

这也取决于你在做什么。如果某些事情已经在进行中,tat将继续运行。不是你必须有状态机才能让它停止。

最新更新