小编kha*_*our的帖子

当包含它的服务停止时,协程不会停止

我有一个前台服务会延迟更改壁纸,因此我在其中使用协程,我使用 startService(Intent(this,MySerivce::class.java)) 从另一个类调用它,但是当我使用 stopService 停止它时(Intent(this,MySerivce::class.java)),仅在主线程停止时起作用(如 showNotification()),这是我的代码:

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val externalStorageState = Environment.getExternalStorageState()
    if (externalStorageState.equals(Environment.MEDIA_MOUNTED)){


    val root=getExternalFilesDir(null)?.absolutePath
        val myDir = File("$root/saved_images")
        val list = myDir.listFiles()
        if (myDir.exists()&&list.size>=2){
            CoroutineScope(Dispatchers.IO).launch {
                val time = intent?.getIntExtra("TIME",0)
                if (time != null) {
                    manageWallpapers(list,time)
                }

            }
        }}

    
    showNotification()
    
    return START_STICKY
}
}
Run Code Online (Sandbox Code Playgroud)

这是管理壁纸功能

private suspend fun manageWallpapers(list: Array<File>?, time:Int){

    while (true){
        if (list != null) {
            for (image in list){

                setWallpaper(image)
                delay(time.toLong())
                
            }
        }

    }

    
}
Run Code Online (Sandbox Code Playgroud)

java android kotlin foreground-service kotlin-coroutines

4
推荐指数
2
解决办法
2745
查看次数