Android感知当前App应用处于前台(可见)或后台(不可见)简洁规范的解决方案
判断当前App是否处于前台(可见)或后台(不可见)附录1是一种解决方案。然而不够简洁,也是在过去一段时间比较稳定的解决方案。现在谷歌官方推出了LifecycleObserver和与Android生命周期相关的Lifecycle维护和管理方案,那么现在判断App处于前台和后台的解决就简洁多了,如代码:
package zhangphil.test;
import android.app.Application;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.arch.lifecycle.ProcessLifecycleOwner;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
//Logger初始化。
Logger.addLogAdapter(new AndroidLogAdapter());
ProcessLifecycleOwner.get().getLifecycle().addObserver(new MyLifecycleObserver());
}
public class MyLifecycleObserver implements LifecycleObserver {
//App处于前台可见状态。
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void create() {
System.out.println("create");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void start() {
System.out.println("start");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void resume() {
System.out.println("resume");
}
//此后App进入不可见状态/后台
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void pause() {
System.out.println("pause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void stop() {
System.out.println("stop");
}
}
}
需要引入依赖:
compile "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
附录:
1,《Android判断当前App应用处于前台(可见)或后台(不可见)》