0

After reading all the answers for questions like "how can I know if my Android app is in the background/foreground" I am still unsure what to do while an interstitial is running?

The preferred answer is basically to track it yourself by manually tracking onPause and onResume or using the new lifecycle library from Google. This works well, however this assumes you control the code for all the activities, when an interstitial runs that isn't your own Activity so this method won't work for it.

Other answers involve calling ActivityManager.getRunningAppProcesses() or ActivityManager.getRunningTasks(). These are of course not recommend and shouldn't be used. I'm also guessing future policy changes might limit this.

So how can I know if my app is on the foreground even while showing an interstitial ad?

Since someone might ask why I need to know this. My app uses the WebView. The WebView has a nasty habit of letting Javascript continue to run even when onPause() is called on the WebView. The only way I have found of stopping it is to run webView.pauseTimers() but that method applies to all WebViews, not just the one you called it on. So if I call that on when my onPause() is called on my Activity right before an interstitial ad, then the interstitial ad will probably freeze and might even ANR.

casolorz
  • 8,486
  • 19
  • 93
  • 200

1 Answers1

-1

If you have Application class ,you can use that class to track.

public class StarterApplication extends Application implements LifecycleObserver {
 @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  public void onAppBackgrounded() {
    //App in background ,do your background stuff
    Log.d( "onAppBackgrounded: ","called");

}

 @OnLifecycleEvent(Lifecycle.Event.ON_START)
  public void onAppForegrounded() {
    // App in foreground,do your foreground stuff
    Log.d("onAppForegrounded: ","called");

}
androidLearner
  • 1,654
  • 1
  • 7
  • 13
  • Don't you have to add the `LifecycleObserver` to each `Activity` by calling `getLifecycle().addObserver()`? That won't work for `interstitials` because I don't control the code of their activities. – casolorz May 25 '21 at 16:31