前言
在日常开发中,随着项目功能越来越多,业务也越来越复杂,普通的项目结构也就不适合团队协作,分享一种项目组件化后全局获取应用上下文的方案。
1.定义Application接口,供Module实现
interface IModuleInit {
fun onCreate() {}
fun attachBaseContext(base: Context) {}
fun onLowMemory() {}
fun onTrimMemory(level: Int) {}
fun onTerminate() {}
}
2.Module实现类
abstract class BaseModuleInit: IModuleInit {
/**
* 模块初始化优先级 越高初始化越快
* Module中设置优先级越小越优先初始化
*/
open val priority: Int = 0
}
3.Module代理类
object ModuleInitDelegate : IModuleInit {
private val moduleList = mutableListOf<IModuleInit>()
fun register(vararg modules: IModuleInit) {
moduleList.addAll(modules)
}
fun reorder() {
moduleList.sortBy { (it as BaseModuleInit).priority }
}
override fun onCreate() {
moduleList.forEach { it.onCreate() }
}
override fun attachBaseContext(base: Context) {
moduleList.forEach { it.attachBaseContext(base) }
}
override fun onLowMemory() {
moduleList.forEach { it.onLowMemory() }
}
override fun onTrimMemory(level: Int) {
moduleList.forEach { it.onTrimMemory(level) }
}
override fun onTerminate() {
moduleList.forEach { it.onTerminate() }
}
}
4.让Application继承自ApplicationProvider
open class ApplicationProvider : Application() {
companion object {
// 全局共享的 Application
lateinit var appContext: Application
}
override fun onCreate() {
super.onCreate()
appContext = this
ModuleInitDelegate.reorder()
ModuleInitDelegate.onCreate()
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
ModuleInitDelegate.attachBaseContext(base)
}
override fun onLowMemory() {
super.onLowMemory()
ModuleInitDelegate.onLowMemory()
}
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
ModuleInitDelegate.onTrimMemory(level)
}
override fun onTerminate() {
super.onTerminate()
ModuleInitDelegate.onTerminate()
}
}
5.在组件中定义ModuleInit类,继承自BaseModuleInit类,做初始化相关
class ModuleInit: BaseModuleInit() {
override fun onCreate() {
val context = ApplicationProvider.appContext
ImageLoader.getDefault().diskCacheOptions()
.setDiskCacheDirPath(context.getExternalFilesDir("cache")?.path ?: context.filesDir.path)
.setDiskCacheFolderName("image")
.setDiskCacheSize(2 * 1024 * 1024) // 设置磁盘缓存2G
.setBitmapPoolSize(2.0f)
.setMemoryCacheSize(1.5f)
.build()
}
override fun onLowMemory() {
super.onLowMemory()
ImageLoader.getDefault().clearMemory(ApplicationProvider.appContext)
}
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
ImageLoader.getDefault().trimMemory(ApplicationProvider.appContext, level)
}
}
6.在Application中注册
class AppContext : ApplicationProvider() {
init {
ModuleInitDelegate.register(ModuleInit(), ModuleInit1(), ModuleInit2())
}
}
7.应用上下文获取
- 使用共享的Application
ApplicationProvider.appContext