我怎么知道我的应用程序是否已被最小化?

时间:2014-09-17 01:13:10

标签: android android-activity

在(至少)两种情况下调用

Activity.onPause()onStop()

  1. 另一个活动是在当前活动的基础上推出的。
  2. 应用程序已最小化。
  3. 有没有一种简单的方法来区分它?

1 个答案:

答案 0 :(得分:2)

你可以这样做。使所有活动从基础活动扩展。基本活动需要保持在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
            }
        }
    };

}