One of the main purposes of managing the app life cycle is to ensure that no data is lost when the user backgrounds or terminates your app. Saving the app state ensures that when the user returns to the app, the app returns to the same condition it was in when it lost focus.
An app can experience a number of interruptions during its life cycle, such as losing focus, low memory events, and low battery events. It is important that your app listen for these events and respond by saving the app state. Any information about the current conditions of the app can be saved. For example, the screen element currently in focus, or any user-entered data, should be saved. The saved state can be reloaded so that when the user returns to the app, the user can then continue on as before.
The type of information you should save about the app state depends upon the app, and upon the likely expectations of your user. For example, for an e-reader app, the user will expect to return to the same page of the same book they were reading. In a text editor app or on a settings page, the user will expect that any text entered is still available, even if those changes were not saved manually. In an interactive game, such as a driving game, you might save much more data about the state of the app. In each case, you must first determine what data is necessary to save so that the user can continue when the saved state is reloaded.
You should save the app state after other significant events such as, in a game app, you might save the state each time the user completes a level.
There are several different methods for saving the app state. The following code example shows how an e-reader app saves and reads the current page number from a file:
#include <stdio.h>
// Save page number to a file
void save_to_file(int page) {
// Open file as binary
FILE *fp = fopen("data/save.dat", "wb");
if (!fp) {
return;
}
fprintf(fp, "%i", page);
fclose(fp);
}
// Retrieve page number from file
// Returns page number or 0, if unsuccessful
int read_from_file() {
int page = 0;
//open file as binary
FILE *fp = fopen("data/save.dat", "rb");
if (!fp) {
return 0;
}
int rc = fscanf(fp, "%i", &page);
if (rc != 1) {
return 0;
}
fclose(fp);
return page;
}