开发者

What is the right place to store persistent app data before exiting?

I have a single Activity application with a data container that is populated at the launch of the application from a JSON formatted private text file. When exiting the application, whether it's a graceful exit or forced one, the the data must be written back to the text file.

Android documentation states that application data shouldn't be saved in the onDestroy method.

I have now overwritten the following methods to make sure the data is stored at exit:

protected void onStop() {
    persistenceManager.storeIfChanged();
    super.开发者_高级运维onStop();
}

protected void onPause() {
    persistenceManager.storeIfChanged();
    super.onPause();
}

The storeIfChanged methods writes the application data to the text file if it has changed since last save. My question is, does this guarantee the application data is saved no matter how the application is terminated (unless it's force majeure). Secondly, is it superfluous to do the saving in both onStop and onPause?


Yes, saving data in onPause is the recommend way. Data will always be saved unless the application is force closed.

Calling it in onPause is enough, onPause is always called before onStop.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜