In my app, I'm working with some huge objects in memory, which are persisted when users use "save" function. The problem is that when the user leaves the app in the background, without saving, after some time, the OS removes those huge objects from memory for increasing free ram memory, so, when the user returns to the app, those objects are null and it crashes.
Does exist a way to know when the OS is killing parts of the app, and block that killing process to store those objects first? If so, I will be able to recover them, but I can't find anything in android documentation.
I know there is a method called onLowMemory
, but it is not the solution, because:
While the exact point at which this will be called is not defined, generally it will happen when all background process have been killed.
http://developer.android.com/reference/android/app/Application.html#onLowMemory%28%29
EDIT: sample code for knowing the app comes to foreground and to background:
public class CustomApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// register observer for knowing when application goes to background and to foreground
ProcessLifecycleOwner.get().getLifecycle().addObserver(new LifecycleObserver(){
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onAppStarted() {
Log.d("XXXX", "onAppStarted() called");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onAppStopped() {
Log.d("XXXX", "onAppStopped() called");
}
});
}
}