Avoiding data loss due to interruption when saving files on android?

前端 未结 5 875
感动是毒
感动是毒 2021-02-07 11:24

I am wondering what strategies others use to avoid data loss when saving files on Android. I have a couple of game apps that and essentially, they potentially save the game stat

5条回答
  •  借酒劲吻你
    2021-02-07 11:45

    We've had occasional issues when we're doing I/O (usually writing) to persistent storage (private filesystem on internal memory) from the main thread. Usually this doesn't take much time at all, but occasionally it inexplicably takes ages (20 or 30 seconds or more). It seems that the Android filesystem implementations on some devices don't support concurrent access (see this, so your I/O can block if another process is using the filesystem. If you are doing your I/O on the main thread, the OS can/will kill your Activity if it blocks for too long. This may be what is happening to you.

    Due to this problem, I would suggest that you move all your I/O to a separate thread (not the main thread). So, for example, to save the game state, in onPause() call a method that serializes the game state to a ByteArrayOutputStream which you then hand off to a separate thread to be written eventually to the filesystem.

提交回复
热议问题