public class ActLifecycle implements ActivityLifecycleCallbacks { private int mPreActivityStartedCount = 0; private int mActivityStartedCount = 0; private int mActivityOrientation = Configuration.ORIENTATION_UNDEFINED; @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { mPreActivityStartedCount = mActivityStartedCount; mActivityStartedCount++; int orientation = getOrientation(activity); if (mPreActivityStartedCount == 0 && mActivityStartedCount == 1 && orientation == mActivityOrientation) { handleAppForeground(activity);//app从后台进入前台了,在这个自定义的方法里处理具体的业务 } mActivityOrientation = orientation; } private int getOrientation(Activity activity) { if (activity != null && activity.getResources() != null) { Configuration configuration = activity.getResources().getConfiguration(); if (configuration != null) { return configuration.orientation; } } return Configuration.ORIENTATION_UNDEFINED; } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { mPreActivityStartedCount = mActivityStartedCount; mActivityStartedCount--; } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { }}
//注册app生命周期回调函数
application.registerActivityLifecycleCallbacks(new ActLifecycle());