Barry Fruitman
Barry Fruitman

Reputation: 12666

How do I know if my app has been minimized?

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?

Upvotes: 2

Views: 486

Answers (1)

mikejonesguy
mikejonesguy

Reputation: 9999

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
            }
        }
    };

}

Upvotes: 2

Related Questions