I want to clear some session data when user directly close the app means if app goes to background I want to clear data, how I recognize that app goes to background, I tried many solutions but they did not work for me,
private boolean isAppIsInBackground(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
isInBackground = false;
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
isInBackground = false;
}
}
return isInBackground;
}
I'm using this method to find the status and I also tried another process which also didn't work for me.
I use Application.ActivityLifecycleCallbacks this process also I'm unable to find and I called this in Application class like this.
public class MyApplicationClass extends Application {
private static final String TAG = MyApplicationClass.class.getSimpleName();
private static MyApplicationClass sInstance;
@Nullable
public static Context getAppContext() {
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"onCreate",Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate() called");
sInstance = this;
registerActivityLifecycleCallbacks(new ActivityCallbackApplication());
}