I am so surprised!
Because not able identify application currently in foreground or background,
when i pressed home button and my application is not in foreground. then after i have used to check application running in foreground or not.
public boolean isAppOnForeground()
{
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) { return false; }
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses)
{
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) { return true; }
}
return false;
}
it will returns always true even if my application actually not in foreground.
Note: My application have 2 services, 1 service will be canceled when application is removed from recent task list( that i have achieved.) 2 service will be canceled when application goes in background. (that is check wifi signal strength.)
how to know app is foreground or background?
how to stop service when application is not in foreground?
Rely on
Activity
callback methods, such asonPause()
,onStop()
andonResume()
, that will give you hints on the current state ofActivity
. The Activity reference gives a very broad explanation of every of those methods.try handling onpause() event of activity class. Onpause is called when activity goes out of focus.