BaseApp.kt 1.95 KB
Newer Older
严久程 committed
1 2 3 4
package com.ydl.ydlcommon.base

import android.app.Application
import android.content.Context
YKai committed
5
import androidx.multidex.MultiDex
严久程 committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
import com.ydl.ydlcommon.base.config.GlobalConfig
import com.ydl.ydlcommon.base.config.IApp
import com.ydl.ydlcommon.base.delegate.AppDelegate
import com.ydl.ydlcommon.base.delegate.IAppLifecycles
import com.ydl.ydlcommon.utils.YDLPreconditions

/**
 * Created by haorui on 2019-08-21 .
 * Des: 基础Application
 */
open class BaseApp : Application(), IApp {

    private var mAppDelegate: IAppLifecycles? = null

    companion object {

        lateinit var instance: BaseApp

        fun getApp(): Application {
            return instance
        }
    }

    /**
     * 这里会在 [BaseApp.onCreate] 之前被调用,可以做一些较早的初始化
     * 常用于 MultiDex 以及插件化框架的初始化
     *
     * @param base
     */
    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        instance = this;
        MultiDex.install(this)
        if (mAppDelegate == null)
            this.mAppDelegate = AppDelegate(base)
        this.mAppDelegate!!.attachBaseContext(base)
    }

    override fun onCreate() {
        super.onCreate()
        if (mAppDelegate != null)
            this.mAppDelegate!!.onCreate(this)

    }

    /**
     * 在模拟环境中程序终止时会被调用
     */
    override fun onTerminate() {
        super.onTerminate()
        if (mAppDelegate != null)
            this.mAppDelegate!!.onTerminate(this)
    }

    override fun getGlobalConfig(): GlobalConfig {
        YDLPreconditions.checkNotNull(
            mAppDelegate,
            "%s cannot be null",
            AppDelegate::class.java.name
        )
        YDLPreconditions.checkState(
            mAppDelegate is IApp,
            "%s must be implements %s",
            mAppDelegate!!::class.java.name,
            IApp::class.java.name
        )

        return (mAppDelegate as IApp).getGlobalConfig()
    }
}