在Application的onCrate()里面执行此方法,直接一个方法就搞定了
/**
* 判断在前台还是后台
*/
public int count = 0;
private void frontOrBack() {
//前后台切换判断
registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
if (count == 0) {
Log.v("vergo", "**********切到前台**********");
}
count++;
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
count--;
if (count == 0) {
Log.v("vergo", "**********切到后台**********");
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}