在Application里监听activity的生命周期变化,代码如下:
package com.test.proj;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
public class MyLifecycleHandler implements Application.ActivityLifecycleCallbacks {
private static int mVisible;
private static int mForeground;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
++mVisible;
if (isApplicationVisible()){
}
}
@Override
public void onActivityResumed(Activity activity) {
++mForeground;
}
@Override
public void onActivityPaused(Activity activity) {
--mForeground;
}
@Override
public void onActivityStopped(Activity activity) {
--mVisible;
if (!isApplicationVisible()){
}
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
public static boolean isApplicationVisible() {
return mVisible > 0;
}
public static boolean isApplicationInForeground() {
// 当所有 Activity 的状态中处于 mForeground 的大于 0 状态的,即可认为有Activity处于前台状态中
return mForeground > 0;
}
}
在app的application的onCreate里注册一下就可以了
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new MyLifecycleHandler());
}
}
就可以了。