I have this code snippet in my Android application, that checks if the app is killed or not.
static boolean isAppKilled(Context appContext) {
boolean appProcessRunning = false;
ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses != null) {
String packageName = appContext.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
System.out.println("LM:appProcess: " + appProcess.processName);
System.out.println("LM:appProcess: " + appProcess.importance);
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE &&
appProcess.processName.equals(packageName)) {
appProcessRunning = true;
break;
}
}
}
return appProcessRunning;
}
But, this snippet returns "true" for the application in the background also, which is not intended.
Can any of you please provide me a code snippet to fulfill all the above cases?
You can implement
LifecycleObserver
interface in youApplication
class and implement lifecycle method:But you need to add dependency to your gradle file:
For more information check the link: https://developer.android.com/topic/libraries/architecture/lifecycle