ActivityLifecycleCallbacks简单介绍

ActivityLifecycleCallbacks提供了一种集中管理Activity生命周期事件的方法,避免了在每个Activity中分别重写生命周期方法。本文介绍了如何使用Application.ActivityLifecycleCallbacks,以及如何在API 14+的设备上实现实时监控应用的前台和后台状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ActivityLifecycleCallbacks是干什么的?

  • 以往若需监测Activity的生命周期事件代码,你可能是这样做的,重写每一个Acivity的onResume(),然后作统计和处理:
  • 或者创建一个BaseActivity,重写onResume().这些都不是很方便,对控制比较分散.
  • 这个可以做到集中化管理.

ActivityLifecycleCallbacks怎么用?

  • android.app.Application.ActivityLifecycleCallbacks
  • 要求API 14+ (Android 4.0+)
  • 继承Application
  • 在AndroidManifest里起用自定义Application
  • <application android:name=".MyApplication"  
  • 重写Application的onCreate()方法,或在Application的无参构造方法内,

    调用Application.registerActivityLifecycleCallbacks()方法,并实现ActivityLifecycleCallbacks接口


    <span style="font-family:microsoft yahei;">public class MyApplication extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
           registerActivityLifecycleCallbacks(MyLifeCycleCallback)
        }
    }

    //实际的使用可以借鉴下面写法!

    public class MyApplication extends Application {
     
        private static final String TAG = "MyApp";
    
        @Override
        public void onCreate() {
            super.onCreate();
            Foreground.init(this);         
        }
    }


    //Foreground.class
  • //通过这个,以后就可以判断程序是否在运行等操作

    import android.app.Activity;
    import android.app.Application;
    import android.content.Context;
    import android.os.Bundle;
    import android.os.Handler;
    
    import java.util.List;
    import java.util.concurrent.CopyOnWriteArrayList;
    
    /**
     * Usage:
     * <p/>
     * 1. Get the Foreground Singleton, passing a Context or Application object unless you
     * are sure that the Singleton has definitely already been initialised elsewhere.
     * <p/>
     * 2.a) Perform a direct, synchronous check: Foreground.isForeground() / .isBackground()
     * <p/>
     * or
     * <p/>
     * 2.b) Register to be notified (useful in Service or other non-UI components):
     * <p/>
     * Foreground.Listener myListener = new Foreground.Listener(){
     * public void onBecameForeground(){
     * // ... whatever you want to do
     * }
     * public void onBecameBackground(){
     * // ... whatever you want to do
     * }
     * }
     * <p/>
     * public void onCreate(){
     * super.onCreate();
     * Foreground.get(this).addListener(listener);
     * }
     * <p/>
     * public void onDestroy(){
     * super.onCreate();
     * Foreground.get(this).removeListener(listener);
     * }
     */
    public class Foreground implements Application.ActivityLifecycleCallbacks {
    
        public static final long CHECK_DELAY = 500;
        public static final String TAG = Foreground.class.getName();
        private static Foreground instance;
        private boolean foreground = false, paused = true;
        private Handler handler = new Handler();
        private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
        private Runnable check;
    
        /**
         * Its not strictly necessary to use this method - _usually_ invoking
         * get with a Context gives us a path to retrieve the Application and
         * initialise, but sometimes (e.g. in test harness) the ApplicationContext
         * is != the Application, and the docs make no guarantees.
         *
         * @param application
         * @return an initialised Foreground instance
         */
        public static Foreground init(Application application) {
            if (instance == null) {
                instance = new Foreground();
                application.registerActivityLifecycleCallbacks(instance);
            }
            return instance;
        }
    
        public static Foreground get(Application application) {
            if (instance == null) {
                init(application);
            }
            return instance;
        }
    
        public static Foreground get(Context ctx) {
            if (instance == null) {
                Context appCtx = ctx.getApplicationContext();
                if (appCtx instanceof Application) {
                    init((Application) appCtx);
                }
                throw new IllegalStateException(
                        "Foreground is not initialised and " +
                                "cannot obtain the Application object");
            }
            return instance;
        }
    
        public static Foreground get() {
            if (instance == null) {
                throw new IllegalStateException(
                        "Foreground is not initialised - invoke " +
                                "at least once with parameterised init/get");
            }
            return instance;
        }
    
        public boolean isForeground() {
            return foreground;
        }
    
        public boolean isBackground() {
            return !foreground;
        }
    
        public void addListener(Listener listener) {
            listeners.add(listener);
        }
    
        public void removeListener(Listener listener) {
            listeners.remove(listener);
        }
    
        @Override
        public void onActivityResumed(Activity activity) {
            paused = false;
            boolean wasBackground = !foreground;
            foreground = true;
    
            if (check != null)
                handler.removeCallbacks(check);
    
            if (wasBackground) {
    //            Log.i(TAG, "went foreground");
                for (Listener l : listeners) {
                    try {
                        l.onBecameForeground();
                    } catch (Exception exc) {
    //                    Log.e(TAG, "Listener threw exception!", exc);
                    }
                }
            } else {
    //            Log.i(TAG, "still foreground");
            }
        }
    
        @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");
                        for (Listener l : listeners) {
                            try {
                                l.onBecameBackground();
                            } catch (Exception exc) {
    //                            Log.e(TAG, "Listener threw exception!", exc);
                            }
                        }
                    } else {
    //                    Log.i(TAG, "still foreground");
                    }
                }
            }, CHECK_DELAY);
        }
    
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        }
    
        @Override
        public void onActivityStarted(Activity activity) {
        }
    
        @Override
        public void onActivityStopped(Activity activity) {
        }
    
        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }
    
        @Override
        public void onActivityDestroyed(Activity activity) {
        }
    
        public interface Listener {
    
            public void onBecameForeground();
    
            public void onBecameBackground();
    
        }
    }
    



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值