public class LifecycleCallback implements Application.ActivityLifecycleCallbacks {
private static final String TAG = "LifecycleCallback";
private int count;
private boolean isForeground;
public boolean isForeground() {
return isForeground;
}
/**
* 运行在主线程,如果需要添加一些相对耗时的操作,最好是在子线程操作
*/
@Override
public void onActivityStarted(Activity activity) {
count ++;
isForeground = false;
}
@Override
public void onActivityStopped(Activity activity) {
count --;
if(count == 0) {
isForeground = true;
}else{
isForeground = false;
}
}
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//注册回调
LifecycleCallback callbacks = new LifecycleCallback();
registerActivityLifecycleCallbacks(callbacks);
}
}
网友评论