判断APP是否处于前台小工具
2016-09-23 本文已影响98人
Wang_Yi
原理:
Application在Api14之后添加了新的Callback方法
@Override
public void registerActivityLifecycleCallbacks(ActivityLifecycleCallbacks callback) {
super.registerActivityLifecycleCallbacks(callback);
}
通过该方法我们可以监听所有Activity的生命周期
代码:
/**
* 用于判断App是否在后台
*/
public class AppLifecycleHandler implements Application.ActivityLifecycleCallbacks {
private static int resumed;
private static int paused;
private static int started;
private static int stopped;
public AppLifecycleHandler() {
resetVariables();
}
private void resetVariables() {
resumed = 0;
paused = 0;
started = 0;
stopped = 0;
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
++resumed;
}
@Override
public void onActivityPaused(Activity activity) {
++paused;
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityStarted(Activity activity) {
++started;
}
@Override
public void onActivityStopped(Activity activity) {
++stopped;
android.util.Log.w("test", "application is visible: " + (started > stopped));
}
public static boolean isApplicationVisible() {
return started > stopped;
}
public static boolean isApplicationInForeground() {
return resumed > paused;
}
public static boolean isApplicationInBackground() {
return started == stopped;
}
}
使用方法:
在Application的onCreate方法中初始化
//程序的生命周期监听
registerActivityLifecycleCallbacks(new AppLifecycleHandler ());