views:

28

answers:

1

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

try {
   final ObjectOutputStream os = new ObjectOutputStream(openFileOutput(gameName + ".sav", 0));
   os.writeObject(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?

A: 

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().

Ricardo Villamil