Skip to content

Instantly share code, notes, and snippets.

@MinceMan
Last active January 4, 2016 09:49
Show Gist options
  • Save MinceMan/dbddca3783f860cafc37 to your computer and use it in GitHub Desktop.
Save MinceMan/dbddca3783f860cafc37 to your computer and use it in GitHub Desktop.
This shows how to let your app know that it had been sent to the background. The only thing it doesn't detect is if you turn of the screen and unlock directly to the app. It will detect if you unlock to another app. It can also handle rotation just fine.
public class App extends Application {
// Bunches of application code
public boolean isAppInForeground() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses != null) {
final String packageName = getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
&& appProcess.processName.equals(packageName)) {
return true;
}
}
}
return false;
}
}
public class BaseActivity extends Activity {
private static final String TAG = BaseActivity.class.getSimpleName();
private boolean appSwitchedToBackground;
// Activity code
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "App was in background: " + Boolean.toString(appSwitchedToBackground));
if (appSwitchedToBackground && UserAccount.isUserLoggedIn()) {
UserAccount.fetchUserDetails(UserAccount.getLoggedInUserToken());
}
}
@Override
protected void onStop() {
super.onStop();
appSwitchedToBackground = !EbatesApp.getInstance().isAppInForeground();
}
// Activity code
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment