Reputation: 37681
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");
}
});
}
}
Upvotes: 3
Views: 1337
Reputation: 1007276
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
More accurately, Android terminates your process.
Does exist a way to know when the OS is killing parts of the app
Android does not "[kill] parts of the app". It terminates your process.
And, no, you are not informed when your process is about to be terminated.
and block that killing process to store those objects first?
No.
You can find out when your app overall moves to the background using ProcessLifecycleOwner
. Any time after that occurs, your process could be terminated, for any reason — it is not just memory pressures. The user could revoke a runtime permission via the Settings app, for example.
So, in your case, if you do not want to save the data when changes are being made, you could save the data to a temporary file when your app moves to the background, and restore the data from that temporary file when your process starts back up again.
Upvotes: 1
Reputation: 13
Have you tried using a custom Application class that extends Application.ActivityLifecycleCallbacks? There is also OnTrimMemory in the Application class itself
Upvotes: 0