【问题标题】:Using filesDir on AsyncTask (Kotlin)在 AsyncTask (Kotlin) 上使用 filesDir
【发布时间】:2019-07-15 18:13:25
【问题描述】:

我正在尝试运行访问本地存储的服务,查找哪些项目尚未上传到服务器,然后上传它们。在尝试分配我的文件名时,我一直在我的活动中使用 filesDir。我相信 filesDir 需要一个上下文,而我正在制作的服务没有。有没有替代方案?这是我的代码:

class AuthorizationSaveTask : AsyncTask<Int, Int, String>() {

override fun onPreExecute() {

}

override fun doInBackground(vararg params: Int?): String {

    val startId = params[0]

    //Get data for list view
    var authorizationArrayList = ArrayList<AuthorizationObject>()
    try {
        //Set target file to authorizations.txt
        val targetFile = File(filesDir, "authorizations.txt")
        //Create new file input stream
        val fis = FileInputStream(targetFile)
        //Create new object input stream, using fis
        val ois = ObjectInputStream(fis)
        //write object input stream to object

        //TODO: There has to be a better syntax than this.
        authorizationArrayList = (ois.readObject() as ArrayList<*>).filterIsInstance<AuthorizationObject>() as ArrayList<AuthorizationObject>
        //close object output stream
        ois.close()
        //close file output stream
        fis.close()

    } catch (e: ClassNotFoundException) {
        e.printStackTrace()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return "Service complete $startId"
}

override fun onProgressUpdate(vararg values: Int?) {
    super.onProgressUpdate(*values)
    val counter = values[0]
    Log.i("BEAU", "Service Running $counter")
}

override fun onPostExecute(result: String) {
    Log.i("BEAU", result)
}

感谢您的宝贵时间!如果我可以提供任何其他信息,请告诉我。

【问题讨论】:

  • 明白了!我不会再这样做了。

标签: java android service kotlin android-asynctask


【解决方案1】:

ServiceContext。更确切地说是它的一个子类。因此,您可以像拨打 Activity 一样拨打 getFilesDir()

但是,您发布的代码没有显示Service,而是显示AsyncTask...我不知道您在哪里创建AsyncTask,但您仍然可以将上下文作为参数传递。

编辑 看来 OP 正在寻找一种将Context 传递给AsynkTask 的方法,我编辑了我的答案。

将您的代码更改为:

class AuthorizationSaveTask : AsyncTask<Int, Int, String>(val context: Context)

无论你在哪里创建你的任务都会传递上下文。

val task = AuthorizationSaveTask(this)

您可能还想考虑只传递文件。

class AuthorizationSaveTask : AsyncTask<Int, Int, String>(val saveDir: File)

在你的Activity:

val task = AuthorizationSaveTask(filesDir)

【讨论】:

  • 当然。谢谢你。我正在服务中运行 AsyncTask。那我试试把它作为参数传递。
  • 我编辑了我的答案以反映您的评论。此外,您应该更改问题标题。使用服务这个词有点令人困惑......
猜你喜欢
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 2017-11-15
  • 2019-08-08
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多