I'm wondering if there would be a way to detect if the app closes in a non activity class. My goal is to save all the values inside my Values.java file once the app has either been closed or cleared from the app switcher.
"close" means that when the app has been cleared from the Android App Switcher.
"non activity class" is exactly that, it isn't code for an activity (a.k.a doesn't have a user interface connected to it), it is only a .java file that holds values.
import android.content.Context;
public class Values {
//General Values
public static boolean vibrationEnabled = true;
//Single Player Values
public static float SPBackgroundNumber = 0;
public static boolean resetScoreSP = false;
public void saveAllValues(){
}
}
The reason I want to detect when the app closes is so that the values all inside this .java file can be saved.
The literal answer: have your activity call saveAllValues()
from its onDestroy()
method.
The correct answer: save the data when the data changes. If the data changes frequently (multiple times per second), save it periodically. Once your app is no longer in the foreground, your process can be terminated at any point, and there is no guarantee that any code in your app will be called when that happens.