gpt4 book ai didi

android - 不适当的阻塞方法调用,但暂停函数 'withContext' 只能从协程或另一个暂停函数中调用

转载 作者:行者123 更新时间:2023-12-04 23:46:58 25 4
gpt4 key购买 nike

在我的服务中,我需要调用 onStartCommand一些需要withContext(Dispatchers.IO)的方法而是 CoroutineScope(Dispatchers.IO)喜欢:

  • url = URL(pokemon.linkImage)
  • url.openConnection().getInputStream()
  • fOut= 文件输出流(文件)
  • fOut.flush()
  • fOut.close()

  • 但是 Suspend function 'withContext' should be called only from a coroutine or another suspend function .所以如果 onStartCommand不能是挂起函数,因为它具有覆盖和 withContext无法被 CoroutineScope 调用,因为 Inappropriate blocking method call方法
    val url = URL(pokemon.linkImage)
    val iS = url.openConnection().getInputStream()
    我该如何解决这个问题?
    我的 onStartCommand() :
    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {

    //create the directory on internal storage that will contains all pokemon images
    val path = applicationContext.filesDir.absolutePath
    val dirName = "/pokeimg"
    val dir = File(path, dirName)
    if(!dir.exists())
    dir.mkdir()
    CoroutineScope(Dispatchers.IO).launch {
    //get the list of pokemon when they are loaded from repository
    val listOfPokemon =
    PersistenceSingletonRepository.getInstance(applicationContext).getListOfPokemon()
    //download all the image for each pokemon in the list, but only if the image is
    //not present in the directory
    for(pokemon in listOfPokemon) {
    val imageName = "${pokemon.name}.png"
    val file = File("${dir.absolutePath}/$imageName")
    //check if image not exists on internal storage and if is not an official-artwork
    //images that aren't official-artwork has less quality so don't resize
    if(!file.exists()) {
    //download img
    val url = URL(pokemon.linkImage)
    val iS = url.openConnection().getInputStream()
    val opts = BitmapFactory.Options()
    if (!Utils.isBadImage(pokemon.linkImage)) {
    //request a smaller image
    opts.inSampleSize = 2
    }
    val bitmap = BitmapFactory.decodeStream(iS, null, opts)
    val fOut= FileOutputStream(file)

    bitmap?.compress(Bitmap.CompressFormat.PNG, 100, fOut)
    fOut.flush()
    fOut.close()
    }

    }
    stopSelf()
    }
    return START_NOT_STICKY
    }

    最佳答案

    您可以放心地忽略该警告,已知它有很多误报。您在 IO 调度程序中启动了协程,该调度程序是为阻塞调用而设计的。
    另一方面,使用 ad-hoc CoroutineScope 启动任何东西没有父级也没有生命周期绑定(bind),通常是错误的做法。您应该尊重服务生命周期并取消 onDestroy 中的协程.参见示例 here .

    关于android - 不适当的阻塞方法调用,但暂停函数 'withContext' 只能从协程或另一个暂停函数中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69066847/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com