全局Application

全局Application使用的是Kotlin的顶层属性

import com.epuxun.drink.utli.initApplication

class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
        initApplication(this)
    }
}

新建一个Utlis的kotlin的文件类,在这个类中我们可以提前初始化一些东西,如SharedPreferences

//方便java类调用,必须在package之前
@file: JvmName("Utils")

package com.epuxun.drink.utli

import android.app.Application

lateinit var application: Application

//提前初始化sharedPreferences优化性能
private lateinit var sharedPreferences: SharedPreferences

/**
 * MyApp中初始化
 */
fun initApplication(app: Application) {
    application = app
    sharedPreferences =
        application.getSharedPreferences(application.packageName, Context.MODE_PRIVATE)
}

/**
 * 获取SharedPreferences
 */
fun sharedPreferences(): SharedPreferences {
    return sharedPreferences
}

/**
 * 保存数据到SharedPreferences
 */
fun putSharedPreferences(vararg anys: Any) {
    sharedPreferences.edit().run {
        for (any in anys) {
            when (any) {
                is String -> this.putString(any, any)
                is Int -> this.putInt("$any", any)
                is Long -> this.putLong("$any", any)
                is Float -> this.putFloat("$any", any)
                is Boolean -> this.putBoolean("$any", any)
            }
        }
        apply()
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章