有时候在开发应用程序时需要监听App当前处于前台还是后台来做一些处理,下面代码可作为参考:
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import com.bose.commontools.logger.BoseLogger;
public class UmeLifecycleHandler implements Application.ActivityLifecycleCallbacks {
private static int resumed;
private static int paused;
private static int started;
private static int stopped;
private static int appCount;
private static boolean isRunInBackground;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
++started;
appCount++;
if (isRunInBackground) {
back2App();
}
}
@Override
public void onActivityResumed(Activity activity) {
++resumed;
if (resumed > paused) {
// AppBus.getInstance().post(new BusEventData(BusEventConstants.APP_REOPEN));
}
}
@Override
public void onActivityPaused(Activity activity) {
++paused;
android.util.Log.w("gudd", "application is in foreground: " + (resumed > paused));
Logger.i("gudd application is in foreground: %s", resumed > paused);
}
@Override
public void onActivityStopped(Activity activity) {
++stopped;
appCount--;
if (appCount == 0) {
leaveApp();
}
Logger.i("gudd application is visible: %s", 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;
}
// 从后台回到前台
private void back2App() {
BoseLogger.i("gudd application returned to foreground.");
isRunInBackground = false;
// AppBus.getInstance().post(new EventCode(BusEventConstants.APP_REOPEN));
}
// 离开应用进入后台或退出应用
private void leaveApp() {
Logger.i("gudd application in the background.");
isRunInBackground = true;
}
}
leaveApp()则表示应用当前的状态为进入后台。