Saving the app state

Saving the application state ensures that when the user returns to the application, the application returns to the same condition it was in when it lost focus.

An application can experience a number of interruptions during its life cycle, for example, losing application focus, low memory events, and low battery events. These events must be managed by the application. It is important that your application listen for these events and respond by saving the application state. Any pertinent information about the current conditions of the application can be saved, for example, the screen element currently in focus, or any user-entered data. When the user returns to the application, the saved state can be reloaded and the user can then continue on as before.

The type of information you should save about the application state depends upon the application, and upon the likely expectations of your user. For example, for an e-reader application, the user might simply expect to return to the same page of the same book they were reading. In a text editor application or on a settings page, the user might expect that any text entered would still be 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 application. In each case, to decide what data to save and when to save it, you must first determine what data is necessary for the user to continue when the user contains state is reloaded.

It is also wise to save the application state after other significant events; for example, in a game application, you might save the state each time the user completes a level.

You should not attempt to save the application state after receiving an exit event, because the application will not have enough time to perform any operations before being terminated.

There are several different methods for saving the application state. The following code example shows how an e-reader application would save and read 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;
}