Saving and Restoring the initialized information
The SDK provides two ways for preserving and restoring the ThingIFAPI
instance that is created upon the initialization.
Saving and Restoring upon the Process Relaunch
The Android system will reconstruct application and Activity instances when the application is moved into the background or when the language setting is changed. When this happens, the ThingIFAPI
instance will be trashed, and all initialized information will be lost.
To restore the ThingIFAPI
instance with all Thing-IF SDK related information upon the Activity reconstruction, please save the instance as a Bundle in the application. To save, use the Parcelable
interface implemented by the ThingIFAPI
in the Activity#onSaveInstanceState
. To restore, implement the restoration logic in the Activity#onCreate
method.
Here is the sample code for saving and restoring the initialized information.
public class AppActivity extends Activity {
private static final String BUNDLE_KEY_THING_IF_API = "ThingIFAPI";
private ThingIFAPI mApi = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
// Restore a Thing-IF API.
mApi = savedInstanceState.getParcelable(BUNDLE_KEY_THING_IF_API);
}
setContentView(R.layout.activity_second);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save a Thing-IF API.
outState.putParcelable(BUNDLE_KEY_THING_IF_API, mApi);
}
}
You can use any key name for the bundle.
In the above sample code, we are restoring the state in the Activity#onCreate
method. You can optionally restore the state in the Activity#onRestoreInstanceState
method.
To learn more about the activity lifecycle in Android, please read the documentation by Google.
Serializing in the Storage
If you need to save the ThingIFAPI
instance for a long time, you can use the serialization feature to save it in the storage (i.e., Android's shared preferences).
Saving the instance to the storage is automatically made by the SDK.
After the process relaunched, you can restore the instance as follows:
try {
// Load a Thing-IF API.
ThingIFAPI api = ThingIFAPI.loadFromStoredInstance(getApplicationContext());
} catch (StoredThingIFAPIInstanceNotFoundException e) {
// Handle the error.
}
If you've created multiple ThingIFAPI
instances with dedicated tags, you can specify the instance to restore with its tag. Simply pass the tag name as the second argument of the loadFromStoredInstance
method. Please read the Initializing and Onboarding to learn more about the tag.
You can delete the preserved instance with the removeStoredInstance
method. Please refer to the Javadoc for more details.
When saving to the shared preferences, we use the key names ThingIFAPI_INSTANCE
or ThingIFAPI_INSTANCE_tag name
. All information previously stored with these keys will be overwritten.