1.自己写一个生命周期的回调
public class MyLifecycleHandler implements Application.ActivityLifecycleCallbacks {
private static int resumed;
private static int paused;
private static int started;
private static int stopped;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
++started;
}
@Override
public void onActivityResumed(Activity activity) {
++resumed;
}
@Override
public void onActivityPaused(Activity activity) {
++paused;
android.util.Log.w("test", "application is in foreground: " + (resumed > paused));
}
@Override
public void onActivityStopped(Activity activity) {
++stopped;
android.util.Log.w("test", "application is visible: " + (started > stopped));
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
public static boolean isApplicationVisible() {
return started > stopped;
}
public static boolean isApplicationInForeground() {
// 当所有 Activity 的状态中处于 resumed 的大于 paused 状态的,即可认为有Activity处于前台状态中
return resumed > paused;
}
}
2.在Application中进行注册
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new MyLifecycleHandler());
}
}
3.在BaseActivity中进行状态的判断
public class BaseActivity extends Activity {
public static boolean isForeground;
private static final String TAG = "BaseActivity";
@Override
protected void onResume() {
super.onResume();
if (MyLifecycleHandler.isApplicationInForeground()){
isForeground = true;
Log.e(TAG, "onResume: --->在前台");
}else{
isForeground = false;
Log.e(TAG, "onResume: --->在后台");
}
}
@Override
protected void onStop() {
super.onStop();
if (MyLifecycleHandler.isApplicationInForeground()){
isForeground = true;
Log.e(TAG, "onStop: ---->在前台");
}else{
isForeground = false;
Log.e(TAG, "onStop: ---->在后台");
}
}
}