存在着各种各样的判断当前程序是否退出前台放置在后台运行的方法,这里提供一种利用Application.ActivityLifecycleCallbacks回调方法实现判断程序是否在前台运行。
步骤一:自定义实现Application.ActivityLifecycleCallbacks回调接口的类Foreground。
public class Foreground implements Application.ActivityLifecycleCallbacks { //单例 private static Foreground instance = new Foreground(); private static String TAG = Foreground.class.getSimpleName(); private final int CHECK_DELAY = 500; //用于判断是否程序在前台 private boolean foreground = false, paused = true; //handler用于处理切换activity时的短暂时期可能出现的判断错误 private Handler handler = new Handler(); private Runnable check; public static void init(Application app){ app.registerActivityLifecycleCallbacks(instance); } public static Foreground get(){ return instance; } private Foreground(){} @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // TODO Auto-generated method stub } @Override public void onActivityDestroyed(Activity activity) { // TODO Auto-generated method stub } @Override public void onActivityPaused(Activity activity) { paused = true; if (check != null) handler.removeCallbacks(check); handler.postDelayed(check = new Runnable(){ @Override public void run() { if (foreground && paused) { foreground = false; Log.i(TAG, "went background"); } else { Log.i(TAG, "still foreground"); } } }, CHECK_DELAY); } @Override public void onActivityResumed(Activity activity) { paused = false; foreground = true; if (check != null) handler.removeCallbacks(check); } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // TODO Auto-generated method stub } @Override public void onActivityStarted(Activity activity) { // TODO Auto-generated method stub } @Override public void onActivityStopped(Activity activity) { // TODO Auto-generated method stub } public boolean isForeground(){ return foreground; } }利用Application.ActivityLifecycleCallbacks回调接口,其实现的原理与观察者模式的原理是相似的,Application提供的一个注册回调接口的方法Application.registerActivityLifecycleCallbacks,传入ActivityLifecycleCallbacks,而Application中定义了ArrayList<ActivityLifecycleCallbacks>用于存储注册的ActivityLifecycleCallbacks
private ArrayList<ActivityLifecycleCallbacks> mActivityLifecycleCallbacks = new ArrayList<ActivityLifecycleCallbacks>();
,相当于添加被观察者,当程序退出前台进入后台后会触发观察者通知被观察者进而获取到相关信息。
同时,利用到接口ActivityLifecycleCallbacks所提供的回调方法onActivityPaused(Activity activity)、onActivityResumed(Activity activity),当程序退出前台进入后台会触发到方法onActivityPaused(Activity activity),当程序从后台回到前台会触发到方法onActivityResumed(Activity activity)。
步骤二:定义全局Application,把当前Application传入到自定义的实现了ActivityLifecycleCallbacks的类Foreground中,从而调用Application所提供的一个注册回调接口的方法Application.registerActivityLifecycleCallbacks把Foreground实例对象传入到被观察者队列中。
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Foreground.init(this); } }
-----------------------------------------------------------------------------------------------------------------
至此,以上便是利用Application.ActivityLifecycleCallbacks回调方法实现判断程序是否在前台运行的方法。