上代码,没什么好说明的:
补充一点,声明工具类,class 需要更改为 object (类声明时)
private const val FILE_NAME = "global_data" fun put(context: Context, key: String, objects: Any) { var sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) var editor = sp.edit() LogUtil.d("put key $key , value $objects as String") when (objects) { is String -> { LogUtil.d("put info begin -- ") editor.putString(key, objects) } is Int -> { editor.putInt(key, objects) } is Boolean -> { editor.putBoolean(key, objects) } is Float -> { editor.putFloat(key, objects) } is Long -> { editor.putLong(key, objects) } } editor.commit() } fun get(context: Context?, key: String, defaults: Any): Any? { var sp = context!!.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) LogUtil.d(" String info : $defaults , " + (defaults is String)) when (defaults) { is String -> { var info = sp.getString(key, defaults) LogUtil.d("return info :$info") return info } is Int -> { return sp.getInt(key, defaults) } is Boolean -> { return sp.getBoolean(key, defaults) } is Float -> { return sp.getFloat(key, defaults) } is Long -> { return sp.getLong(key, defaults) } } return null } fun remove(context: Context, key: String) { var sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) var editor = sp.edit() editor.remove(key) editor.commit() } fun clear(context: Context) { var sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) var editor = sp.edit() editor.clear() editor.commit() }