android - 如何在 Kotlin 中设置使用 AsyncTask 运行我的代码
问题描述
如何在 Kotlin 中设置使用 AsyncTask 运行我的代码?
- 如何在脚本运行时更新 UI 中的文本标签以及更多描述
- 我如何在我的项目中避免内存泄漏
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)
}
}
}
}
}
请帮我
解决方案
由于您使用的是 Kotlin,因此您应该使用Coroutines。它们是 Kotlin 中多线程的最佳选择。AsyncTask 主要在 Java 中使用,现在已弃用,因此您最好不要再使用它。
有关防止内存泄漏的最佳实践和更多信息,请阅读此。
推荐阅读
- html - 如何在 flex 容器内的 Font Awesome 图标后居中跨度?
- sftp - SFTP 脚本无法更改目录问题
- javascript - 说店铺是模特对吗?
- html - 如何制作连接到数据库的html登录页面
- python - 获取 pandas 布尔系列为 True 的索引列表
- c# - 使用自定义表数据类型执行存储过程
- asp.net-core - 使用 .NET Core 2.1 实现 Google Open ID Connect 的正确方法是什么?
- javascript - 函数中的异步,等待第一个函数完成,然后再触发下一个函数
- git - 无法从 origin/ 提交文件
到原点/主 - node.js - 带有 Socket.io 和 Express 的 Node.js 聊天应用程序在本地工作,但不在主机上