2

Activity.onPause() and onStop() are called in (at least) two situations:

  1. The another Activity was launched on top of the current one.
  2. The app was minimized.

Is there an easy way to tell the difference?

Barry Fruitman
  • 12,316
  • 13
  • 72
  • 135
  • 2
    Can I ask what the purpose of knowing this is - from an activity lifecycle POV activities only care about if they're visible or not, not the reason why they aren't visible. – Andrew Breen Sep 17 '14 at 01:14
  • When you say `minimized` do you mean when and only when the home button is pressed? – Keale Sep 17 '14 at 01:15
  • @Keale Yes that's what I mean. – Barry Fruitman Sep 17 '14 at 01:17
  • Well I can't run android code on my machine now so I cannot test the following but maybe you can look at [this](http://stackoverflow.com/questions/8881951/detect-home-button-press-in-android), [this](http://stackoverflow.com/questions/2208912/how-can-i-detect-user-pressing-home-key-in-my-activity), and maybe [this](http://stackoverflow.com/questions/15374673/android-see-if-home-key-is-pressed) – Keale Sep 17 '14 at 01:21
  • 1
    @Kaele, None of those will work now. It's not possible to detect home button from 4.0+. – DeeV Sep 17 '14 at 01:28

1 Answers1

2

You could do it this way. Make all of your activities extend from a base activity. The base activity needs to keep a visibility counter that is incremented/decremented during onResume/onPause:

public abstract class MyBaseActivity extends ActionBarActivity {
    private static int visibility = 0;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
    }

    @Override
    protected void onResume() {
        super.onResume();
        visibility++;
        handler.removeCallBacks(pauseAppRunnable);
    }

    @Override
    protected void onPause() {
        super.onPause();
        visibility--;
        handler.removeCallBacks(pauseAppRunnable);
        // give a short delay here to account for the overhead of starting
        // a new activity. Might have to tune this a bit (not tested).
        handler.postDelayed(pauseAppRunnable, 100L);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // uncomment this if you want the app to NOT respond to invisibility 
        // if the user backed out of all open activities.
        //handler.removeCallBacks(pauseAppRunnable);
    }

    private Runnable pauseAppRunnable = new Runnable() {
        @Override
        public void run() {
            if (visibility == 0) {
                // do something about it
            }
        }
    };

}
mikejonesguy
  • 9,779
  • 2
  • 35
  • 49