全局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()
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章