I know this question is not new to stackoverflow, however I am still confused. So please don't mark this question as a duplicate, help me on this!
My android app has many activities. I need to call a web service, when my app comes to foreground and need to call another web service, when my app switched to background.
My initial findings are:
- I read the activity life cycle http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle and realized that I can call the above 2 web services in
- onPause() = when app is switched to background
- onResume() = when app is switched to foreground.
My activity:
protected void onPause()
{
AppUtil.trackAppBackgroundStatus(this);
super.onPause();
}
protected void onResume()
{
super.onResume();
AppUtil.trackAppForegroundStatus(this);
}
My utility class:
public class AppUtil
{
public static void trackAppForegroundStatus(Context theContext)
{
SharedPreferences aSharedSettings = theContext.getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);
String aAppStatus = aSharedSettings.getString("appStatus", "");
if(!aAppStatus.equals("foreground"))
{
SharedPreferences.Editor aPrefEditor = aSharedSettings.edit();
aPrefEditor.putString("appStatus", "foreground");
aPrefEditor.commit();
trackSession(theContext, "foreground");
}
}
public static void trackAppBackgroundStatus(Context theContext)
{
SharedPreferences aSharedSettings = theContext.getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);
String aAppStatus = aSharedSettings.getString("appStatus", "");
if(!aAppStatus.equals("background"))
{
SharedPreferences.Editor aPrefEditor = aSharedSettings.edit();
aPrefEditor.putString("appStatus", "background");
aPrefEditor.commit();
trackSession(theContext, "background");
}
}
}
The trackSession method will track my app's foreground and background status.
Drawbacks: As said above, my app has various activities. So consider I have Page_A and Page_B.
In Page_A, after the onCreate() method call, control goes to onResume() and tracks that my app is in foreground.. When I move to the next page (Page_B), onPause() method of Page_A is called and tracks that my app is switched to background.
I don't want to track this by every activities.. I need to track my app's background status only when my app goes to background (that is, only when user presses home button and my app is switched to background).
- I also tried with Checking if an Android application is running in the background and the same happens
- getRunningTasks() will solve my issue. However read that, Google will probably reject an app that uses ActivityManager.getRunningTasks().
Can anyone please guide me. Basically, I need to call 2 web-services. One, when app comes to foreground and the second, when app switches to background.
If these calls cannot be made with respect to app, how can I update my above code to handle them.
Any help please.