开发者

Writing Objects from a thread in Android

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜