Android: Writing to a file in AsyncTask

核能气质少年 提交于 2019-12-08 06:26:04

问题


I would love to be able to write to a local directory in my AsyncTask subclass, but I can't seem to figure out how to use getFilesDir(), since I cannot, to my knowledge, create an instance of ContextWrapper and Context in this subclass.

So, what have I tried? I've tried getting the files directory the only way I know how by attempting many different things to create instances of Context and ContextWrapper in order to access the getFilesDir() method. That's it. That's all I know how to do.

I'm probably missing a lot of blatantly obvious things, but I've been working with Android for about 2 days now, so I still don't know how to debug my issues properly.

Any "ExplainLikeImFive" help is greatly appreciated.

EDIT:

From what I know now, you can only get the files directory through an Activity. Why is that?


回答1:


You need to use a Context object to access files in the local directory. You can use an instance of an Activity as your Context object. create an AsyncTask and give it a reference to your Activity. Then in your AsyncTask, you can use the Activity to access the filesystem:

activity.getFilesDir();


来源:https://stackoverflow.com/questions/14204980/android-writing-to-a-file-in-asynctask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!