1、创建MApplication文件
import android.app.Application;
public class MApplication extends Application {
private static MApplication mApplication;
private AppLifecycleHandler lifecycleHandler;
@Override
public void onCreate() {
super.onCreate();
lifecycleHandler = new AppLifecycleHandler(); //register AppLifecycleHandler
lifecycleHandler.onCreate();
}
public static MApplication getInstance() {
if (mApplication == null) {
mApplication = new MApplication();
}
return mApplication;
}
}
2、创建AppLifecycleHandler文件
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* Monitor the application's foreground and background status
*/
public class AppLifecycleHandler implements Application.ActivityLifecycleCallbacks {
private int runningActivities = 0;
private static final String GET_APP_CONFIG_DEFAULT_TIMESTAMP = "0";
private static final long ONE_SECOND = 1000L;
private static long timeToBackground = 0L;
@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
if (runningActivities == 0) {
//应用在前台
}
runningActivities++;
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
runningActivities--;
if (runningActivities == 0) {
//应用在后台
}
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
}
public void onCreate() {
MApplication.getInstance().registerActivityLifecycleCallbacks(this);
}
}