开发者

Writing Objects from a thread in Android

开发者 https://www.devze.com 2023-01-08 23:33 出处:网络
I have a game object that I save like this in OnPause() try { final ObjectOutputStream os = new ObjectOutputStream(openFileOutput(gameName + \".sav\", 0));

I have a game object that I save like this in OnPause()

try {
   final ObjectOutputStream os = new ObjectOutputStream(openFileOutput(gameName + ".sav", 0));
   os.writeObje开发者_JAVA技巧ct(gameObject);
   os.reset();
  } catch (final Exception e) {
   e.printStackTrace();

}

This works fine except on some of the older or slower phones it can sometimes take too long to complete. I end up getting a ANR (Activity Not Responding) error. I would like to move this to a thread to prevent blocking the UI. However when I try this I run into multiple problems.

First openFileOutput is only available in my activity. I worked around this by passing the ObjectOutputStream to the thread. After that I could save the object but later when I tried to reload I get a java.io.EOFExeception.

Does anyone have a good pattern for writing objects to a file from a thread?


Here you go: http://developer.android.com/guide/appendix/faq/commontasks.html#threading

Just move your code into the run() method of the thread and call startLongRunningOperation() in your activity's onPause().

0

精彩评论

暂无评论...
验证码 换一张
取 消