判断Android前后台切换的方法
自定义在Application,在Application中注册registerActivityLifecycleCallbacks监听所有的Activity,在onActivityStarted和onActivityStopped事件中进行处理。registerActivityLifecycleCallbacks只有在API 14才增加的。代码如下:
public class AppNameApplication extends Application { private int activityCount; @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { @Override public void onActivityStarted(Activity activity) { activityCount++; if (activityCount== 1){ //从后台切换到前台 } } @Override public void onActivityStopped(Activity activity) { activityCount--; if (activityCount== 0){ //从前台切换到后台 } } }); } }