首页 > 解决方案 > 如何在 Kotlin 中设置使用 AsyncTask 运行我的代码

问题描述

如何在 Kotlin 中设置使用 AsyncTask 运行我的代码?


 public fun zipAll(directory: String, zipFile: String) {
    val sourceFile = File(directory.toUri().path)
    ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use {
        it.use {
             zipFiles(it, sourceFile, "")
        }
    }
}
    private fun zipFiles(zipOut: ZipOutputStream, sourceFile: File, parentDirPath: String) {
    val data = ByteArray(2048)
    val dialogBuilder = AlertDialog.Builder(this!!)
    val textLabel = findViewById<TextView>(R.id.textView_progress)
    var i = 0
    sourceFile.listFiles()?.forEach { f ->
        i++
            FileInputStream(f).use { fi ->
                BufferedInputStream(fi).use { origin ->
                    val path = parentDirPath + File.separator + f.name
                    val entry = ZipEntry(path)
                    entry.time = f.lastModified()
                    entry.isDirectory
                    entry.size = f.length()
                    zipOut.putNextEntry(entry)
                    Log.i("listView ", "$i")
                    textLabel.setText("hello $i")
                    while (true) {
                        val readBytes = origin.read(data)
                        if (readBytes == -1) {
                            break
                        }
                        zipOut.write(data, 0, readBytes)
                    }
                }
            
        }
    }
}

请帮我

标签: androidandroid-studioandroid-layoutkotlinmobile

解决方案


由于您使用的是 Kotlin,因此您应该使用Coroutines。它们是 Kotlin 中多线程的最佳选择。AsyncTask 主要在 Java 中使用,现在已弃用,因此您最好不要再使用它。

有关防止内存泄漏的最佳实践和更多信息,请阅读


推荐阅读