代码之家  ›  专栏  ›  技术社区  ›  giuseppebrb

Android-在标准java类中使用活动回调

  •  2
  • giuseppebrb  · 技术社区  · 7 年前

    callback onCreate() 在…上 onResume() ,等等)。 我有办法做到吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Krish    7 年前

    据我所知,你需要这样的东西,

    import android.app.Activity;
    import android.app.Application;
    import android.os.Bundle;
    
    /**
     * @Krish
     */
    
    public class LifeCycleObserver {
    
        private LifeCycleObserver() {}
    
        private static LifeCycleObserver sLifeCycleObserver;
    
        public static LifeCycleObserver getInstance()
        {
            if (sLifeCycleObserver == null)
            {
                sLifeCycleObserver = new LifeCycleObserver();
            }
    
            return sLifeCycleObserver;
        }
    
    
        public static void init(Application application)
        {
            application.registerActivityLifecycleCallbacks(sLifeCycleObserver.lifecycleCallbacks);
        }
    
    
        private Application.ActivityLifecycleCallbacks lifecycleCallbacks = new Application.ActivityLifecycleCallbacks() {
    
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    
            }
    
            @Override
            public void onActivityStarted(Activity activity) {
    
            }
    
            @Override
            public void onActivityResumed(Activity activity) {
    
            }
    
            @Override
            public void onActivityPaused(Activity activity) {
    
            }
    
            @Override
            public void onActivityStopped(Activity activity) {
    
            }
    
            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    
            }
    
            @Override
            public void onActivityDestroyed(Activity activity) {
    
            }
        };
    
    }
    

    在应用程序类中这样使用,

    导入android.app.Application;

    /**
     * Created by krish
     */
    
    public class MyApplication extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
            LifeCycleObserver.init(this);
        }
    }