Newer
Older
DevAndroid / app / src / main / java / keijumt / devandroid / App.kt
package keijumt.devandroid

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.app.FragmentManager
import dagger.android.AndroidInjection
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjection
import dagger.android.support.DaggerApplication
import dagger.android.support.HasSupportFragmentInjector
import keijumt.devandroid.di.Injectable
import keijumt.devandroid.di.Injector

class App : DaggerApplication() {

    // 現在のActivity
    var currentActivity: Activity? = null

    companion object {
        /**
         * Activity に dagger#inject を注入
         *
         * @param activity 注入したい Activity instance
         */
        private fun handleActivity(activity: Activity) {
            if (activity is HasSupportFragmentInjector) {
                AndroidInjection.inject(activity) /// Inject!!!!
            }
            (activity as? FragmentActivity)?.supportFragmentManager?.registerFragmentLifecycleCallbacks(
                    object : FragmentManager.FragmentLifecycleCallbacks() {
                        override fun onFragmentCreated(fm: FragmentManager?, f: Fragment?,
                                                       savedInstanceState: Bundle?) {
                            if (f is Injectable) {
                                AndroidSupportInjection.inject(f)
                            }
                        }
                    }, true)
        }
    }

    override fun onCreate() {
        super.onCreate()
        setupActivityLifecycle()
    }

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return Injector.setup(this)
    }

    /**
     * Activity ライフサイクル カスタマイズ
     */
    private fun setupActivityLifecycle() {
        registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityPaused(activity: Activity?) {
            }

            override fun onActivityResumed(activity: Activity?) {
            }

            override fun onActivityStarted(activity: Activity?) {
            }

            override fun onActivityDestroyed(activity: Activity?) {
            }

            override fun onActivitySaveInstanceState(activity: Activity?, bundle: Bundle?) {
            }

            override fun onActivityStopped(activity: Activity?) {
                if (currentActivity === activity) {
                    currentActivity = null
                }
            }

            override fun onActivityCreated(activity: Activity?, bundle: Bundle?) {
                activity?.let {
                    handleActivity(it)
                }
            }

        })
    }
}