diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 0611528d..ab0df177 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -85,6 +85,7 @@ dependencies { implementation ("androidx.core:core-splashscreen:1.0.1") implementation ("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7") implementation ("com.google.android.material:material:1.12.0") + implementation (kotlin("stdlib", version = kotlinVersion)) implementation ("com.github.cachapa:ExpandableLayout:2.9.2") implementation ("com.squareup.picasso:picasso:2.71828") @@ -97,12 +98,13 @@ dependencies { implementation("com.google.android.gms:play-services-location:21.3.0") implementation("com.google.android.gms:play-services-tasks:18.2.0") implementation("com.squareup.retrofit2:retrofit:2.9.0") - implementation("com.squareup.retrofit2:converter-gson:2.6.4") + implementation("com.squareup.retrofit2:converter-gson:2.9.0") implementation("com.squareup.retrofit2:converter-scalars:2.6.4") - implementation("androidx.viewpager2:viewpager2:1.0.0") + implementation("androidx.viewpager2:viewpager2:1.1.0") implementation("com.squareup.picasso:picasso:2.71828") implementation("com.github.delight-im:Android-AdvancedWebView:v3.2.1") implementation(project(":library")) + implementation(project(":utils")) // implementation ("me.everything:providers-android:1.0.1") // implementation ("me.everything:providers-core:1.0.1") // implementation ("androidx.window:window:1.0.0") diff --git a/app/src/main/kotlin/bums/lunatic/launcher/LauncherActivity.kt b/app/src/main/kotlin/bums/lunatic/launcher/LauncherActivity.kt index 1c0f83b5..a3631c6d 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/LauncherActivity.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/LauncherActivity.kt @@ -85,7 +85,9 @@ import bums.lunatic.launcher.helpers.Constants.Companion.KEY_STATUS_BAR import bums.lunatic.launcher.helpers.Constants.Companion.PREFS_FIRST_LAUNCH import bums.lunatic.launcher.helpers.Constants.Companion.PREFS_SETTINGS import bums.lunatic.launcher.helpers.Constants.Companion.widgetHostId +import bums.lunatic.launcher.helpers.PrefBoolean import bums.lunatic.launcher.helpers.PrefHelper +import bums.lunatic.launcher.helpers.PrefLong import bums.lunatic.launcher.helpers.letTrue import bums.lunatic.launcher.home.LauncherHome import bums.lunatic.launcher.home.LauncherHome.Companion.lastedFinishedPageUrl @@ -160,7 +162,7 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.enqueueUniquePeriodicWork( SMS_WORK_TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.longTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.longTimePeriod.get(), TimeUnit.MINUTES) .addTag(SMS_WORK_TAG) .build()) }, 500, TimeUnit.MILLISECONDS) @@ -169,7 +171,7 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.enqueueUniquePeriodicWork( RecentCallGetter.TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.longTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.longTimePeriod.get(), TimeUnit.MINUTES) .addTag(RecentCallGetter.TAG) .build()) }, 500, TimeUnit.MILLISECONDS) @@ -211,12 +213,18 @@ internal class LauncherActivity : AppCompatActivity() { } fun refreshFeeds() { +// Fri, 15 11 2024 15:06:28 +0900 +// Fri, 15 11 2024 15:28:04 +0900 + var parseDateFormat2: SimpleDateFormat = SimpleDateFormat("E, dd MM yyyy HH:mm:ss zz", Locale.ENGLISH) + BLog.LOGE("TEST DATE FORMAT ${parseDateFormat2.format(Date())}") + var parseDateFormat3: SimpleDateFormat = SimpleDateFormat("E, dd MM yyyy HH:mm:ss ZZ", Locale.ENGLISH) + BLog.LOGE("TEST DATE FORMAT ${parseDateFormat3.format(Date())}") var delay = 5L Executors.newSingleThreadScheduledExecutor().schedule({ mWorkManager?.cancelAllWorkByTag(FEDDS_WORK_TAG) mWorkManager?.enqueueUniquePeriodicWork( FEDDS_WORK_TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.shortTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.shortTimePeriod.get(), TimeUnit.MINUTES) .addTag(FEDDS_WORK_TAG) .build()) }, delay, TimeUnit.SECONDS) @@ -225,7 +233,7 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.cancelAllWorkByTag(YT_WORK_TAG) mWorkManager?.enqueueUniquePeriodicWork( YT_WORK_TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.longTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.longTimePeriod.get(), TimeUnit.MINUTES) .addTag(YT_WORK_TAG) .build()) }, delay, TimeUnit.SECONDS) @@ -234,7 +242,7 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.cancelAllWorkByTag(REDDIT_WORK_TAG) mWorkManager?.enqueueUniquePeriodicWork( REDDIT_WORK_TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.midTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.midTimePeriod.get(), TimeUnit.MINUTES) .addTag(REDDIT_WORK_TAG) .build()) }, delay, TimeUnit.SECONDS) @@ -243,7 +251,7 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.cancelAllWorkByTag(COMIC_WORK_TAG) mWorkManager?.enqueueUniquePeriodicWork( COMIC_WORK_TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.midTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.midTimePeriod.get(), TimeUnit.MINUTES) .addTag(COMIC_WORK_TAG) .build()) }, delay, TimeUnit.SECONDS) @@ -252,7 +260,7 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.cancelAllWorkByTag(COMIC2_WORK_TAG) mWorkManager?.enqueueUniquePeriodicWork( COMIC2_WORK_TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.midTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.midTimePeriod.get(), TimeUnit.MINUTES) .addTag(COMIC2_WORK_TAG) .build()) }, delay, TimeUnit.SECONDS) @@ -261,7 +269,7 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.cancelAllWorkByTag(ClienGetter.TAG) mWorkManager?.enqueueUniquePeriodicWork( ClienGetter.TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.midTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.midTimePeriod.get(), TimeUnit.MINUTES) .addTag(ClienGetter.TAG) .build()) }, delay, TimeUnit.SECONDS) @@ -270,7 +278,7 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.cancelAllWorkByTag(DCGetter.TAG) mWorkManager?.enqueueUniquePeriodicWork( DCGetter.TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.midTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.midTimePeriod.get(), TimeUnit.MINUTES) .addTag(DCGetter.TAG) .build()) }, delay, TimeUnit.SECONDS) @@ -279,7 +287,7 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.cancelAllWorkByTag(RuliWebGetter.TAG) mWorkManager?.enqueueUniquePeriodicWork( RuliWebGetter.TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.midTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.midTimePeriod.get(), TimeUnit.MINUTES) .addTag(RuliWebGetter.TAG) .build()) }, delay, TimeUnit.SECONDS) @@ -288,7 +296,7 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.cancelAllWorkByTag(TheQooGetter.TAG) mWorkManager?.enqueueUniquePeriodicWork( TheQooGetter.TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.midTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.midTimePeriod.get(), TimeUnit.MINUTES) .addTag(TheQooGetter.TAG) .build()) }, delay, TimeUnit.SECONDS) @@ -297,22 +305,22 @@ internal class LauncherActivity : AppCompatActivity() { mWorkManager?.cancelAllWorkByTag(ArcaGetter.TAG) mWorkManager?.enqueueUniquePeriodicWork( ArcaGetter.TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.midTimePeriod, TimeUnit.MINUTES) + PeriodicWorkRequestBuilder(PrefLong.midTimePeriod.get(), TimeUnit.MINUTES) .addTag(ArcaGetter.TAG) .build()) }, delay, TimeUnit.SECONDS) - val weatherDelay = 3L - Executors.newSingleThreadScheduledExecutor().schedule({ - //de574a260b1f474d99955729241909 - mWorkManager?.cancelAllWorkByTag(LocationGetter.TAG) - mWorkManager?.enqueueUniquePeriodicWork( - LocationGetter.TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, - PeriodicWorkRequestBuilder(PrefHelper.longTimePeriod, TimeUnit.MINUTES) - .addTag(LocationGetter.TAG) - .build()) - }, weatherDelay, TimeUnit.SECONDS) +// val weatherDelay = 3L +// Executors.newSingleThreadScheduledExecutor().schedule({ +// //de574a260b1f474d99955729241909 +// mWorkManager?.cancelAllWorkByTag(LocationGetter.TAG) +// mWorkManager?.enqueueUniquePeriodicWork( +// LocationGetter.TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, +// PeriodicWorkRequestBuilder(PrefLong.longTimePeriod.get(), TimeUnit.MINUTES) +// .addTag(LocationGetter.TAG) +// .build()) +// }, weatherDelay, TimeUnit.SECONDS) // Executors.newSingleThreadScheduledExecutor().schedule({ // //de574a260b1f474d99955729241909 @@ -473,10 +481,10 @@ internal class LauncherActivity : AppCompatActivity() { } fun updateLocationService() { - PrefHelper.isLocationOn().letTrue { + PrefBoolean.location.get().letTrue { startService(Intent(this, LocationUpdateService::class.java)) } - if (PrefHelper.isLocationOn() == false) { + if (PrefBoolean.location.get() == false) { stopService(Intent(this, LocationUpdateService::class.java)) } } diff --git a/app/src/main/kotlin/bums/lunatic/launcher/LunaticLauncher.kt b/app/src/main/kotlin/bums/lunatic/launcher/LunaticLauncher.kt index e7f6a496..daec1da6 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/LunaticLauncher.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/LunaticLauncher.kt @@ -33,7 +33,7 @@ internal class LunaticLauncher : Application() { override fun onCreate() { super.onCreate() appContext = this - PrefHelper.inject(getSharedPreferences(PrefHelper.D_PREFIX, Context.MODE_PRIVATE)) + PrefHelper.initialize(this) } override fun onTrimMemory(level: Int) { super.onTrimMemory(level) diff --git a/app/src/main/kotlin/bums/lunatic/launcher/feeds/Feeds.kt b/app/src/main/kotlin/bums/lunatic/launcher/feeds/Feeds.kt index 88c5d6e5..1a6b4c3e 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/feeds/Feeds.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/feeds/Feeds.kt @@ -66,7 +66,9 @@ import bums.lunatic.launcher.helpers.Constants.Companion.PREFS_WIDGETS import bums.lunatic.launcher.helpers.Constants.Companion.SEPARATOR import bums.lunatic.launcher.helpers.Constants.Companion.requestCreateWidget import bums.lunatic.launcher.helpers.Constants.Companion.requestPickWidget +import bums.lunatic.launcher.helpers.PrefBoolean import bums.lunatic.launcher.helpers.PrefHelper +import bums.lunatic.launcher.helpers.PrefString import bums.lunatic.launcher.home.LauncherHome.Companion.home import bums.lunatic.launcher.home.LauncherHome.Companion.listTags import bums.lunatic.launcher.model.CiliMagnet @@ -237,15 +239,15 @@ internal class Feeds : Fragment() , CommadCallabck { } "car" -> { if (cmd[1].trim().length > 2) { - PrefHelper.carName = cmd[1].trim() + PrefString.carName.set(cmd[1].trim()) } - consoleLog(PrefHelper.carName) + consoleLog(PrefString.carName.get()) } "tt" -> { if (cmd[1].trim().length > 5) { - PrefHelper.telegramSendTarget = cmd[1].trim() + PrefString.telegramSendTarget.set(cmd[1].trim()) } - consoleLog(PrefHelper.telegramSendTarget) + consoleLog(PrefString.telegramSendTarget.get()) } "so"-> { CoroutineScope(Dispatchers.IO).launch { @@ -401,8 +403,8 @@ internal class Feeds : Fragment() , CommadCallabck { FeedsResult().show(parentFragmentManager, "") } "loc_on" -> { - PrefHelper.location(!PrefHelper.isLocationOn()) - consoleLog("PrefHelper.isLocationOn() >>> ${PrefHelper.isLocationOn()}") + PrefBoolean.location.set(!PrefBoolean.location.get()) + consoleLog("PrefHelper.isLocationOn() >>> ${PrefBoolean.location.get()}") lActivity?.updateLocationService() } "cal" ->{ diff --git a/app/src/main/kotlin/bums/lunatic/launcher/helpers/BluetoothManager.kt b/app/src/main/kotlin/bums/lunatic/launcher/helpers/BluetoothManager.kt index 47ca17d6..35a8b3aa 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/helpers/BluetoothManager.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/helpers/BluetoothManager.kt @@ -75,9 +75,9 @@ class BluetoothManager { // BLog.LOGE("getPairedDevices() / name : ${i.name}") // BLog.LOGE("getPairedDevices() / bondState : ${i.bondState}") val isConnected = isConnected(i) - if(PrefHelper.carName.length > 2 && i.name.equals(PrefHelper.carName) && isConnected != PrefHelper.isConnectedCar) { - PrefHelper.isConnectedCar = isConnected - sendToI(PrefHelper.isConnectedCar) + if(PrefString.carName.get().length > 2 && i.name.equals(PrefString.carName.get()) && isConnected != PrefBoolean.isConnectedCar.get()) { + PrefBoolean.isConnectedCar.set(isConnected) + sendToI(PrefBoolean.isConnectedCar.get()) } } } @@ -85,13 +85,13 @@ class BluetoothManager { fun sendToI(boolean: Boolean) { - if (PrefHelper.telegramSendTarget.length > 5) { + if (PrefString.telegramSendTarget.get().length > 5) { CoroutineScope(Dispatchers.IO).launch { val url = - "https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/sendMessage?chat_id=${PrefHelper.telegramSendTarget}&text=${if(boolean) { - "돼지가 ${PrefHelper.carName}에 탔다요." + "https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/sendMessage?chat_id=${PrefString.telegramSendTarget.get()}&text=${if(boolean) { + "돼지가 ${PrefString.carName.get()}에 탔다요." }else { - "${PrefHelper.carName}의 시동이 꺼졌다요." + "${PrefString.carName.get()}의 시동이 꺼졌다요." }}" //7068729507 // OkHttp 클라이언트 객체 생성 diff --git a/app/src/main/kotlin/bums/lunatic/launcher/helpers/PrefHelper.kt b/app/src/main/kotlin/bums/lunatic/launcher/helpers/PrefHelper.kt index 21a546e7..c8ebcba7 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/helpers/PrefHelper.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/helpers/PrefHelper.kt @@ -1,30 +1,38 @@ package bums.lunatic.launcher.helpers import android.content.SharedPreferences +import kr.lunaticbum.utils.preferences.PrefJsonConvert +import kr.lunaticbum.utils.preferences.PrefKey +import kr.lunaticbum.utils.preferences.PreferencesHelper -enum class PrefString { + +enum class PrefString : PrefKey { + defaultTimeFormat, + defaultDateFormat, weatherApiKey, locationApi, telegramBotApi, telegramMyId, telegramSendTarget, carName; - fun set(value : String) = PrefHelper.putString(this.name, value) - fun get(def : String? = null) : String = PrefHelper.getString(this.name, def as? String ?: "") ?: "" + override fun set(value: String) {PrefHelper.putString(this.name, value)} + override fun get(def : String?) : String = PrefHelper.getString(this.name, def as? String ?: "") ?: "" + override fun getKey() = this.name } -enum class PrefLong { - locationTimePeriod, - locationDistance, - shortTimePeriod, - longTimePeriod, - midTimePeriod, - maxQueryCount; - fun set(value : Long) = PrefHelper.putLong(this.name, value) - fun get(def : Long? = null) : Long = PrefHelper.getLong(this.name, def as? Long ?: 0L) ?: 0L +enum class PrefLong(val def : Long) : PrefKey { + locationTimePeriod(20L), + locationDistance(200L), + shortTimePeriod(20L), + longTimePeriod(60L), + midTimePeriod(30L), + maxQueryCount(18L); + override fun set(value : Long) { PrefHelper.putLong(this.name, value) } + override fun get(def : Long?) : Long = PrefHelper.getLong(this.name, def as? Long ?: this.def) ?: 0L + override fun getKey() = this.name } -enum class PrefBoolean { +enum class PrefBoolean : PrefKey { location, rootPermisssion, isConnectedCar, @@ -39,129 +47,44 @@ enum class PrefBoolean { showNewsHistory, showNowPlaying, ; - fun set(value : Boolean) = PrefHelper.putBoolean(this.name, value) - fun get(def : Boolean? = null) : Boolean = PrefHelper.getBoolean(this.name, def as? Boolean ?: false) ?: false -} -enum class PrefKey { - TYPE_STRING, - locationApi, - telegramBotApi, - telegramSendTarget, - carName, - TYPE_LONG, - shortTimePeriod, - longTimePeriod, - midTimePeriod, - maxQueryCount, - TYPE_BOOL, - location, - isConnectedCar, - useQuickLaunch, - openWithKayboard, - showAppResultCount, - TYPE_END; - - fun set(value : Any): Unit { - when(this.ordinal) { - in (TYPE_STRING.ordinal..TYPE_LONG.ordinal) -> { - (value as? String)?.let { PrefHelper.putString(this.name, it) } - } - in (TYPE_LONG.ordinal..TYPE_BOOL.ordinal) -> { - (value as? Long)?.let { PrefHelper.putLong(this.name, it) } - } - in (TYPE_BOOL.ordinal..TYPE_END.ordinal) -> { - (value as? Boolean)?.let { PrefHelper.putBoolean(this.name, it) } - } - else -> {} - } - } - - fun get(def : Any? = null) : Any? { - when(this.ordinal) { - in (TYPE_STRING.ordinal..TYPE_LONG.ordinal) -> { - return PrefHelper.getString(this.name, def as? String ?: "") - } - in (TYPE_LONG.ordinal..TYPE_BOOL.ordinal) -> { - return PrefHelper.getLong(this.name, def as? Long ?: 0L) - } - in (TYPE_BOOL.ordinal..TYPE_END.ordinal) -> { - return PrefHelper.getBoolean(this.name, def as? Boolean ?: false) - } - else -> {} - } - return null + override fun set(value : Boolean) { + PrefHelper.putBoolean(this.name, value) } + override fun get(def : Boolean?) : Boolean = PrefHelper.getBoolean(this.name, def as? Boolean ?: false) ?: false + override fun getKey() = this.name } -object PrefHelper { - val D_PREFIX = "rasel.lunar.launcher.helpers" - val BOOL_PRE = D_PREFIX.plus(".BOOL.") - val STRING_PRE = D_PREFIX.plus(".STRING.") - val LONG_PRE = D_PREFIX.plus(".LONG.") - fun inject(SharedPreferences : SharedPreferences) { - this.sharedPreferences = SharedPreferences +object PrefHelper : PreferencesHelper() { + override fun getDefaultPrefix(): String { return "rasel.lunar.launcher.helpers" } + + override fun getSettings() : Map { + var jsonObj = HashMap() + PrefString.values().forEach { jsonObj.put(it.name,it.get("")) } + PrefBoolean.values().forEach { jsonObj.put(it.name,it.get(false)) } + PrefLong.values().forEach { jsonObj.put(it.name,it.get(0L)) } + return jsonObj + } + + override fun putSetting(json : Map) { + PrefString.values().forEach { if(json.containsKey(it.getKey())) { it.set(json.get(it.getKey()) as String) } } + PrefBoolean.values().forEach { if(json.containsKey(it.getKey())) { it.set(json.get(it.getKey()) as Boolean) } } + PrefLong.values().forEach { if(json.containsKey(it.getKey())) { it.set(json.get(it.getKey()) as Long) } } } - var sharedPreferences : SharedPreferences? = null - fun getBoolean(key : String, def :Boolean) = this.sharedPreferences?.getBoolean(BOOL_PRE.plus(key),def) ?: def - fun putBoolean(key : String, value :Boolean) = this.sharedPreferences?.edit()?.putBoolean(BOOL_PRE.plus(key),value)?.apply() - fun getLong(key : String, def :Long) = this.sharedPreferences?.getLong(LONG_PRE.plus(key),def) ?: def - fun putLong(key : String, value :Long) = this.sharedPreferences?.edit()?.putLong(LONG_PRE.plus(key),value)?.apply() - fun getString(key : String, def :String) = this.sharedPreferences?.getString(STRING_PRE.plus(key),def) ?: def - fun putString(key : String, value :String) = this.sharedPreferences?.edit()?.putString(STRING_PRE.plus(key),value)?.apply() - fun location(boolean: Boolean) = PrefKey.location.set(boolean) - fun isLocationOn() = (PrefKey.location.get() as? Boolean) ?: false - - var locationApi : String - get() = PrefKey.locationApi.get() as? String ?: "" - set(value) = PrefKey.locationApi.set(value) - - var telegramBotApi : String - get() = PrefKey.telegramBotApi.get() as? String ?: "" - set(value) = PrefKey.telegramBotApi.set(value) - - var telegramSendTarget : String - get() = PrefKey.telegramSendTarget.get() as? String ?: "" - set(value) = PrefKey.telegramSendTarget.set(value) - - var carName : String - get() = PrefKey.carName.get() as? String ?: "" - set(value) = PrefKey.carName.set(value) - - - var shortTimePeriod : Long - get() = PrefKey.shortTimePeriod.get(20L) as? Long ?: 20L - set(value) = PrefKey.shortTimePeriod.set(value) - - var longTimePeriod : Long - get() = PrefKey.longTimePeriod.get(60L) as? Long ?: 60L - set(value) = PrefKey.longTimePeriod.set(value) - - var midTimePeriod : Long - get() = PrefKey.midTimePeriod.get(30L) as? Long ?: 30L - set(value) = PrefKey.midTimePeriod.set(value) - - - var isConnectedCar : Boolean - get() = PrefKey.isConnectedCar.get() as? Boolean ?: false - set(value) = PrefKey.isConnectedCar.set(value) - - var useQuickLaunch : Boolean - get() = PrefKey.useQuickLaunch.get() as? Boolean ?: false - set(value) = PrefKey.useQuickLaunch.set(value) - - var openWithKayboard : Boolean - get() = PrefKey.openWithKayboard.get() as? Boolean ?: false - set(value) = PrefKey.openWithKayboard.set(value) - - var showAppResultCount : Boolean - get() = PrefKey.showAppResultCount.get() as? Boolean ?: false - set(value) = PrefKey.showAppResultCount.set(value) + fun getBoolean(key : String, def :Boolean) = get(getBooleanPrefix().plus(key),def) + fun putBoolean(key : String, value :Boolean) = put(getBooleanPrefix().plus(key),value) + fun getLong(key : String, def :Long) = get(getLongPrefix().plus(key),def) + fun putLong(key : String, value :Long) = put(getBooleanPrefix().plus(key),value) + fun getString(key : String, def :String) = get(getStringPrefix().plus(key),def) + fun putString(key : String, value :String) = put(getStringPrefix().plus(key),value) +// fun location(boolean: Boolean) = PrefBoolean.location.set(boolean) +// fun isLocationOn() = (PrefBoolean.location.get() as? Boolean) ?: false } + typealias BLOCK = ()->Unit inline fun Boolean.letTrue(block: BLOCK) { if (this) { diff --git a/app/src/main/kotlin/bums/lunatic/launcher/home/LauncherHome.kt b/app/src/main/kotlin/bums/lunatic/launcher/home/LauncherHome.kt index f007663b..e9d770fc 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/home/LauncherHome.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/home/LauncherHome.kt @@ -1056,7 +1056,7 @@ internal class LauncherHome : Fragment() { } override fun onClick(targetView: View, fingers: Int): Boolean { - BLog.LOGE("onClick ${view} , fingers ${fingers}") +// BLog.LOGE("onClick ${view} , fingers ${fingers}") targetView.performHapticFeedback(HapticFeedbackConstants.CONFIRM) when (fingers) { 1 -> { diff --git a/app/src/main/kotlin/bums/lunatic/launcher/home/adapters/RssFeedsParser.kt b/app/src/main/kotlin/bums/lunatic/launcher/home/adapters/RssFeedsParser.kt index d98e0616..14e11978 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/home/adapters/RssFeedsParser.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/home/adapters/RssFeedsParser.kt @@ -4,6 +4,7 @@ import android.util.Xml import bums.lunatic.launcher.model.NewsData import bums.lunatic.launcher.model.RssDataInterface import bums.lunatic.launcher.model.others.Reddit +import bums.lunatic.launcher.utils.BLog import bums.lunatic.launcher.utils.beforeDay import com.google.gson.Gson import org.xmlpull.v1.XmlPullParser @@ -19,6 +20,7 @@ import java.util.Locale object RssFeedsParser { var parseDateFormat: SimpleDateFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH) + var parseDateFormat2: SimpleDateFormat = SimpleDateFormat("E, dd MM yyyy HH:mm:ss ZZ", Locale.ENGLISH) var limitDateTime = beforeDay(Date(),3) fun getFeeds(url : String) : List { var returnList = mutableListOf() @@ -97,11 +99,9 @@ object RssFeedsParser { } else if (name == "link") { link = readLink(parser) } else if (name == "pubDate") { - try { - date = parseDateFormat.parse(readDate(parser))?.time ?: 0L - }catch (e : Exception) { - e.printStackTrace() - } + val dateStr = readDate(parser) + try { date = parseDateFormat.parse(dateStr)?.time ?: 0L } catch (e : Exception) { date = 0L } finally { BLog.LOGE("readFeed >>> parse 1 date ${date}") } + if (date == 0L) { try { date = parseDateFormat2.parse(dateStr)?.time ?: 0L } catch (e: Exception) { } } } else if (name == "description") { desc = readDesc(parser) } else if (name == "source") { @@ -142,9 +142,14 @@ object RssFeedsParser { @Throws(XmlPullParserException::class, IOException::class) private fun readDate(parser: XmlPullParser): String { - parser.require(XmlPullParser.START_TAG, null, "pubDate") - val date = readText(parser) - parser.require(XmlPullParser.END_TAG, null, "pubDate") + var date = "" + try { + parser.require(XmlPullParser.START_TAG, null, "pubDate") + date = readText(parser) + parser.require(XmlPullParser.END_TAG, null, "pubDate") + } catch (e : Exception) { + + } return date } diff --git a/app/src/main/kotlin/bums/lunatic/launcher/settings/childs/Apps.kt b/app/src/main/kotlin/bums/lunatic/launcher/settings/childs/Apps.kt index 37f3da37..d6485b29 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/settings/childs/Apps.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/settings/childs/Apps.kt @@ -27,8 +27,8 @@ import android.view.View import android.view.ViewGroup import bums.lunatic.launcher.R import bums.lunatic.launcher.databinding.SettingsAppsBinding +import bums.lunatic.launcher.helpers.PrefBoolean import bums.lunatic.launcher.helpers.PrefHelper -import bums.lunatic.launcher.helpers.PrefKey import bums.lunatic.launcher.helpers.PrefLong import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog @@ -63,26 +63,26 @@ internal class Apps : BottomSheetDialogFragment() { packageManager = requireActivity().packageManager - binding.keyboardAutoGroup.isChecked = PrefHelper.openWithKayboard + binding.keyboardAutoGroup.isChecked = PrefBoolean.openWithKayboard.get() binding.keyboardAutoGroup.setOnCheckedChangeListener { c,v -> settingsChanged = true - PrefHelper.openWithKayboard = v + PrefBoolean.openWithKayboard.set(v) } - binding.quickLaunchGroup.isChecked = PrefHelper.useQuickLaunch + binding.quickLaunchGroup.isChecked = PrefBoolean.useQuickLaunch.get() binding.quickLaunchGroup.setOnCheckedChangeListener { c,v -> settingsChanged = true - PrefHelper.useQuickLaunch = v + PrefBoolean.useQuickLaunch.get(v) } - binding.appsCountGroup.isChecked = PrefHelper.showAppResultCount + binding.appsCountGroup.isChecked = PrefBoolean.showAppResultCount.get() binding.appsCountGroup.setOnCheckedChangeListener { c,v -> settingsChanged = true - PrefHelper.showAppResultCount = v + PrefBoolean.showAppResultCount.set(v) } - ((PrefKey.maxQueryCount.get(18L) as? Long)?.toFloat() ?: 18F).let { + ((PrefLong.maxQueryCount.get(18L) as? Long)?.toFloat() ?: 18F).let { binding.columnsCountTitle.text = getString(R.string.grid_columns_count) +" [${it.toInt()}]" binding.columnsCount.value = it } @@ -124,23 +124,23 @@ internal class Apps : BottomSheetDialogFragment() { binding.columnsCount.addOnChangeListener(Slider.OnChangeListener { _, value, _ -> settingsChanged = true - PrefKey.maxQueryCount.set(value.toLong()) + PrefLong.maxQueryCount.set(value.toLong()) binding.columnsCountTitle.text = getString(R.string.grid_columns_count) +" [${value.toInt()}]" }) binding.shortTime.addOnChangeListener(Slider.OnChangeListener { _, value, _ -> settingsChanged = true - PrefKey.shortTimePeriod.set(value.toLong()) + PrefLong.shortTimePeriod.set(value.toLong()) binding.shortTimeTitle.text = getString(R.string.shortTimeTitle) +" [${value.toInt()}분 마다]" }) binding.middleTime.addOnChangeListener(Slider.OnChangeListener { _, value, _ -> settingsChanged = true - PrefKey.midTimePeriod.set(value.toLong()) + PrefLong.midTimePeriod.set(value.toLong()) binding.middleTimeTitle.text = getString(R.string.middleTimeTitle) +" [${value.toInt()}분 마다]" }) binding.longTime.addOnChangeListener(Slider.OnChangeListener { _, value, _ -> settingsChanged = true - PrefKey.longTimePeriod.set(value.toLong()) + PrefLong.longTimePeriod.set(value.toLong()) binding.longTimeTitle.text = getString(R.string.longTimeTitle) +" [${value.toInt()}]분 마다]" }) diff --git a/app/src/main/kotlin/bums/lunatic/launcher/settings/childs/TimeDate.kt b/app/src/main/kotlin/bums/lunatic/launcher/settings/childs/TimeDate.kt index a1b0f7a1..613cc663 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/settings/childs/TimeDate.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/settings/childs/TimeDate.kt @@ -23,6 +23,8 @@ import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import androidx.core.widget.doAfterTextChanged +import bums.lunatic.launcher.R import bums.lunatic.launcher.databinding.SettingsTimeDateBinding import bums.lunatic.launcher.helpers.Constants.Companion.DEFAULT_DATE_FORMAT import bums.lunatic.launcher.helpers.Constants.Companion.KEY_DATE_FORMAT @@ -30,25 +32,34 @@ import bums.lunatic.launcher.helpers.Constants.Companion.KEY_TIME_FORMAT import bums.lunatic.launcher.settings.SettingsActivity.Companion.settingsPrefs import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import java.text.SimpleDateFormat +import java.util.Date import java.util.Objects +import kotlin.system.exitProcess internal class TimeDate : BottomSheetDialogFragment() { private lateinit var binding : SettingsTimeDateBinding - + private var settingsChanged: Boolean = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = SettingsTimeDateBinding.inflate(inflater, container, false) + binding.timeFormat.doAfterTextChanged { + try { + SimpleDateFormat(it.toString()).format(Date()) + binding.previewDateTime + } catch (e : Exception) { - /* initialize views according to the saved values */ - when (settingsPrefs!!.getInt(KEY_TIME_FORMAT, 0)) { - 0 -> binding.followSystemTime.isChecked = true - 1 -> binding.selectTwelve.isChecked = true - 2 -> binding.selectTwentyFour.isChecked = true + } } + binding.dateFormat.doAfterTextChanged { + try { + it.toString() + } catch (e : Exception) { - binding.dateFormat - .setText(settingsPrefs!!.getString(KEY_DATE_FORMAT, DEFAULT_DATE_FORMAT).toString()) + } + } return binding.root } @@ -58,22 +69,23 @@ internal class TimeDate : BottomSheetDialogFragment() { (requireDialog() as BottomSheetDialog).dismissWithAnimation = true /* change time format value */ - binding.timeGroup.setOnCheckedStateChangeListener { group, _ -> - when (group.checkedChipId) { - binding.followSystemTime.id -> settingsPrefs!!.edit().putInt(KEY_TIME_FORMAT, 0).apply() - binding.selectTwelve.id -> settingsPrefs!!.edit().putInt(KEY_TIME_FORMAT, 1).apply() - binding.selectTwentyFour.id -> settingsPrefs!!.edit().putInt(KEY_TIME_FORMAT, 2).apply() - } - } + } /* if the input field is empty, then save the default value. else save the value from input field while closing the dialog */ override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) - val dateFormat = Objects.requireNonNull(binding.dateFormat.text).toString().trim { it <= ' ' } - if (dateFormat.isEmpty()) settingsPrefs!!.edit().putString(KEY_DATE_FORMAT, DEFAULT_DATE_FORMAT).apply() - else settingsPrefs!!.edit().putString(KEY_DATE_FORMAT, dateFormat).apply() + if (settingsChanged) { + MaterialAlertDialogBuilder(requireActivity()) + .setTitle(R.string.restart_now) + .setMessage(R.string.restart_message) + .setPositiveButton(R.string.restart) { _, _ -> + exitProcess(0) + } + .setNeutralButton(R.string.later, null) + .show() + } } } diff --git a/app/src/main/kotlin/bums/lunatic/launcher/view/DateTimeView.kt b/app/src/main/kotlin/bums/lunatic/launcher/view/DateTimeView.kt index 9fb63d40..1ba145a1 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/view/DateTimeView.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/view/DateTimeView.kt @@ -23,8 +23,16 @@ import java.util.Date class DateTimeView : AppCompatTextView { lateinit var mHandler : Handler - val simpleTimeFormat = SimpleDateFormat("a HH:mm:ss") - val simpleDateFormat = SimpleDateFormat("yyyy년 MM월 W주차 dd일 E요일") + var defaultTimeFormat = "a HH:mm:ss" + set(value) { + field = value + } + var defaultDateFormat = "yyyy년 MM월 W주차 dd일 E요일" + set(value) { + field = value + } + var simpleTimeFormat = SimpleDateFormat(defaultTimeFormat) + var simpleDateFormat = SimpleDateFormat(defaultDateFormat) var runable = { setTime() } @@ -47,6 +55,7 @@ class DateTimeView : AppCompatTextView { val spannableBuilder = SpannableStringBuilder() + private fun setTime() { spannableBuilder.clear() val now = Date(System.currentTimeMillis()) diff --git a/app/src/main/kotlin/bums/lunatic/launcher/workers/LocationGetter.kt b/app/src/main/kotlin/bums/lunatic/launcher/workers/LocationGetter.kt index 3cfbc68e..2eb58304 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/workers/LocationGetter.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/workers/LocationGetter.kt @@ -5,6 +5,7 @@ import android.content.Context import android.location.Location import androidx.work.WorkerParameters import bums.lunatic.launcher.LauncherActivity.Companion.runWeatherGetter +import bums.lunatic.launcher.helpers.PrefBoolean import bums.lunatic.launcher.helpers.PrefHelper import bums.lunatic.launcher.helpers.letTrue import bums.lunatic.launcher.utils.BLog @@ -34,7 +35,7 @@ class LocationGetter(context: Context, workerParams: WorkerParameters) : BaseGet longitude = it.longitude latitude = it.latitude runWeatherGetter() - PrefHelper.isLocationOn().letTrue { + PrefBoolean.location.get().letTrue { pushLocation(this.applicationContext,it.latitude, it.longitude) } } diff --git a/app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt b/app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt index 2422a2c9..73ee6df7 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt @@ -1,6 +1,7 @@ package bums.lunatic.launcher.workers import android.Manifest +import android.annotation.SuppressLint import android.app.Service import android.content.Context import android.content.Intent @@ -14,6 +15,7 @@ import android.os.IBinder import android.widget.Toast import androidx.core.app.ActivityCompat import bums.lunatic.launcher.LauncherActivity.Companion.runWeatherGetter +import bums.lunatic.launcher.helpers.PrefBoolean import bums.lunatic.launcher.helpers.PrefHelper import bums.lunatic.launcher.helpers.PrefLong import bums.lunatic.launcher.helpers.PrefString @@ -140,7 +142,7 @@ class LocationUpdateService : Service(), LocationListener { override fun onLocationChanged(p0: Location) { BLog.LOGE("p0") - PrefHelper.isLocationOn().letTrue { + PrefBoolean.location.get().letTrue { longitude = p0.longitude latitude = p0.latitude runWeatherGetter() @@ -148,14 +150,44 @@ class LocationUpdateService : Service(), LocationListener { } } + @SuppressLint("MissingPermission") override fun onCreate() { super.onCreate() - location + try{ + locationManager = applicationContext + .getSystemService(LOCATION_SERVICE) as LocationManager + checkGPS = locationManager!! + .isProviderEnabled(LocationManager.GPS_PROVIDER) + checkNetwork = locationManager!! + .isProviderEnabled(LocationManager.NETWORK_PROVIDER) + locationManager?.requestLocationUpdates( + LocationManager.GPS_PROVIDER, + PrefLong.locationTimePeriod.get(30), + PrefLong.locationDistance.get(200).toFloat(), + this + ) +// val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) +// fusedLocationClient.lastLocation.addOnSuccessListener { location -> +// if (location != null) { +// Toast.makeText( +// applicationContext, +// java.lang.Double.toString(location.latitude) + location.longitude + "from method", +// Toast.LENGTH_LONG +// ).show() +// longitude = location.longitude +// latitude = location.latitude +// runWeatherGetter() +// pushLocation(this.applicationContext, location.latitude, location.longitude) +// } +// } + } catch (e : Exception) { + + } } private val location: Location? - private get() { + get() { if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION diff --git a/app/src/main/kotlin/bums/lunatic/launcher/workers/NewsFeedsGetter.kt b/app/src/main/kotlin/bums/lunatic/launcher/workers/NewsFeedsGetter.kt index e72cf6d4..d685628e 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/workers/NewsFeedsGetter.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/workers/NewsFeedsGetter.kt @@ -6,6 +6,7 @@ import androidx.work.WorkerParameters import bums.lunatic.launcher.home.adapters.RssFeedsParser import bums.lunatic.launcher.model.RssDataType import bums.lunatic.launcher.model.getRssData +import bums.lunatic.launcher.utils.BLog import bums.lunatic.launcher.utils.RssList class NewsFeedsGetter : BaseGetter { @@ -24,6 +25,7 @@ class NewsFeedsGetter : BaseGetter { feddsUrls.addAll(RssList.getFeedUrls()) for (url in feddsUrls) { + BLog.LOGE("start newsFeeds Load By url >>>> ${url}") for (it in RssFeedsParser.getFeeds(url)) { if (it.pubDate() >= limitDateTime) { temp.add(it.getRssData()) diff --git a/app/src/main/res/layout/settings_time_date.xml b/app/src/main/res/layout/settings_time_date.xml index f0062359..bc7aaf7c 100644 --- a/app/src/main/res/layout/settings_time_date.xml +++ b/app/src/main/res/layout/settings_time_date.xml @@ -1,49 +1,59 @@ - + + + + + app:layout_constraintTop_toBottomOf="@id/previewDateTime"/> - + app:layout_constraintTop_toBottomOf="@+id/timeDateTitle"> - - - - + + + app:layout_constraintTop_toBottomOf="@+id/timeFormatParent"> + \ No newline at end of file diff --git a/utils/src/main/java/kr/lunaticbum/utils/preferences/Pref.java b/utils/src/main/java/kr/lunaticbum/utils/preferences/Pref.java deleted file mode 100644 index 487dae75..00000000 --- a/utils/src/main/java/kr/lunaticbum/utils/preferences/Pref.java +++ /dev/null @@ -1,9 +0,0 @@ -package kr.lunaticbum.utils.preferences; - -/** - * Pref is abbreviation class of {@link PreferencesUtil}. - * - * @author Robin Gustafsson - */ -public class Pref extends PreferencesUtil { -} diff --git a/utils/src/main/java/kr/lunaticbum/utils/preferences/PreferencesUtil.kt b/utils/src/main/java/kr/lunaticbum/utils/preferences/PreferencesUtil.kt index 80a465fc..7fe0e578 100644 --- a/utils/src/main/java/kr/lunaticbum/utils/preferences/PreferencesUtil.kt +++ b/utils/src/main/java/kr/lunaticbum/utils/preferences/PreferencesUtil.kt @@ -15,201 +15,126 @@ import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.io.Serializable -/** - * PreferencesUtil helps to manage application-wide [SharedPreferences] conveniently. - * - * @author Robin Gustafsson - */ -open class PreferencesUtil { - companion object { - private val LogHelper = LogHelper(PreferencesUtil::class.java) - var defaultName: String = PreferencesUtil::class.java.canonicalName - - private fun getPreferences(name: String): SharedPreferences { - return getContext().getSharedPreferences(name, Context.MODE_PRIVATE) - } - fun get(key: String?, defValue: Boolean): Boolean { - return get(defaultName, key, defValue) - } +interface PrefKey { + fun getKey() : String + fun set(value : T) + fun get(def : T? = null) : T +} +interface PrefJsonConvert { + fun initialize(context: Context) + fun inject(SharedPreferences : SharedPreferences) + fun getSettings() : Map + fun putSetting(json : Map) +} +abstract class PreferencesHelper : PrefJsonConvert { - fun get(key: String?, defValue: Int): Int { - return get(defaultName, key, defValue) - } + var sharedPreferences : SharedPreferences? = null + open fun allPrefKeys() : ArrayList =arrayListOf() + open fun getBooleanPrefix() : String = getDefaultPrefix().plus(".BOOL.") + open fun getStringPrefix() : String = getDefaultPrefix().plus(".STRING.") + open fun getLongPrefix() : String = getDefaultPrefix().plus(".LONG.") + open fun getDefaultPrefix() : String = PreferencesHelper::class.java.canonicalName + abstract override fun getSettings() : Map + abstract override fun putSetting(json : Map) - fun get(key: String?, defValue: Float): Float { - return get(defaultName, key, defValue) - } + private val LogHelper = LogHelper(PreferencesHelper::class.java) - fun get(key: String?, defValue: Long): Long { - return get(defaultName, key, defValue) - } + override fun initialize(context: Context) { + inject(context.getSharedPreferences(getDefaultPrefix(), Context.MODE_PRIVATE)) + } - fun get(key: String?, defValue: String?): String? { - return get(defaultName, key, defValue) - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - fun get(key: String?, defValue: Set?): Set? { - return get(defaultName, key, defValue) - } - - @TargetApi(Build.VERSION_CODES.FROYO) - fun get(key: String?, defValue: C): C { - return get(defaultName, key, defValue) - } - - fun get(name: String, key: String?, defValue: Boolean): Boolean { - return getPreferences(name).getBoolean(key, defValue) - } - - fun get(name: String, key: String?, defValue: Int): Int { - return getPreferences(name).getInt(key, defValue) - } - - fun get(name: String, key: String?, defValue: Float): Float { - return getPreferences(name).getFloat(key, defValue) - } - - fun get(name: String, key: String?, defValue: Long): Long { - return getPreferences(name).getLong(key, defValue) - } - - fun get(name: String, key: String?, defValue: String?): String? { - return getPreferences(name).getString(key, defValue) - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - fun get(name: String, key: String?, defValue: Set?): Set? { - return getPreferences(name).getStringSet(key, defValue) - } - - @TargetApi(Build.VERSION_CODES.FROYO) - fun get(name: String, key: String?, defValue: C): C { - var bais: ByteArrayInputStream? = null - var ois: ObjectInputStream? = null - var result = defValue - - val value = getPreferences(name).getString(key, null) - if (value != null) { - try { - val decoded = Base64.decode(value.toByteArray(), Base64.DEFAULT) - bais = ByteArrayInputStream(decoded) - ois = ObjectInputStream(bais) - result = ois.readObject() as C - } catch (e: Exception) { - LogHelper.e(e) - } finally { - if (ois != null) { - try { - ois.close() - } catch (e: IOException) { - LogHelper.e(e) - } - } - if (bais != null) { - try { - bais.close() - } catch (e: IOException) { - LogHelper.e(e) - } - } - } - } - - return result - } + override fun inject(sharedPreferences : SharedPreferences) { + this.sharedPreferences = sharedPreferences + } - fun put(key: String?, value: Boolean) { - put(defaultName, key, value) - } + fun get(key: String?, defValue: Boolean): Boolean { + return get(getDefaultPrefix(), key, defValue) + } - fun put(key: String?, value: Int) { - put(defaultName, key, value) - } + fun get(key: String?, defValue: Int): Int { + return get(getDefaultPrefix(), key, defValue) + } - fun put(key: String?, value: Float) { - put(defaultName, key, value) - } + fun get(key: String?, defValue: Float): Float { + return get(getDefaultPrefix(), key, defValue) + } - fun put(key: String?, value: Long) { - put(defaultName, key, value) - } + fun get(key: String?, defValue: Long): Long { + return get(getDefaultPrefix(), key, defValue) + } - fun put(key: String?, value: String?) { - put(defaultName, key, value) - } + fun get(key: String?, defValue: String?): String? { + return get(getDefaultPrefix(), key, defValue) + } - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - fun put(key: String?, value: Set?) { - put(defaultName, key, value) - } + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + fun get(key: String?, defValue: Set?): Set? { + return get(getDefaultPrefix(), key, defValue) + } - @TargetApi(Build.VERSION_CODES.FROYO) - fun put(key: String?, value: C) { - put(defaultName, key, value) - } + @TargetApi(Build.VERSION_CODES.FROYO) + fun get(key: String?, defValue: C): C { + return get(getDefaultPrefix(), key, defValue) + } - fun put(name: String, key: String?, value: Boolean) { - if (APILevel.require(9)) getPreferences(name).edit().putBoolean(key, value).apply() - else getPreferences(name).edit().putBoolean(key, value).commit() - } + fun get(name: String, key: String?, defValue: Boolean): Boolean { + return getPreferences()?.getBoolean(key, defValue) ?: false + } - fun put(name: String, key: String?, value: Int) { - if (APILevel.require(9)) getPreferences(name).edit().putInt(key, value).apply() - else getPreferences(name).edit().putInt(key, value).commit() - } + fun getPreferences(): SharedPreferences? { + return this.sharedPreferences + } - fun put(name: String, key: String?, value: Float) { - if (APILevel.require(9)) getPreferences(name).edit().putFloat(key, value).apply() - else getPreferences(name).edit().putFloat(key, value).commit() - } + fun get(name: String, key: String?, defValue: Int): Int { + return getPreferences()?.getInt(key, defValue) ?: 0 + } - fun put(name: String, key: String?, value: Long) { - if (APILevel.require(9)) getPreferences(name).edit().putLong(key, value).apply() - else getPreferences(name).edit().putLong(key, value).commit() - } + fun get(name: String, key: String?, defValue: Float): Float { + return getPreferences()?.getFloat(key, defValue) ?: 0f + } - fun put(name: String, key: String?, value: String?) { - if (APILevel.require(9)) getPreferences(name).edit().putString(key, value).apply() - else getPreferences(name).edit().putString(key, value).commit() - } + fun get(name: String, key: String?, defValue: Long): Long { + return getPreferences()?.getLong(key, defValue) ?: 0L + } - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - fun put(name: String, key: String?, value: Set?) { - if (APILevel.require(9)) getPreferences(name).edit().putStringSet(key, value).apply() - else getPreferences(name).edit().putStringSet(key, value).commit() - } + fun get(name: String, key: String?, defValue: String?): String? { + return getPreferences()?.getString(key, defValue) + } - @TargetApi(Build.VERSION_CODES.FROYO) - fun put(name: String, key: String?, value: C) { - var baos: ByteArrayOutputStream? = null - var oos: ObjectOutputStream? = null + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + fun get(name: String, key: String?, defValue: Set?): Set? { + return getPreferences()?.getStringSet(key, defValue) + } + @TargetApi(Build.VERSION_CODES.FROYO) + fun get(name: String, key: String?, defValue: C): C { + var bais: ByteArrayInputStream? = null + var ois: ObjectInputStream? = null + var result = defValue + + val value = getPreferences()?.getString(key, null) + if (value != null) { try { - baos = ByteArrayOutputStream() - oos = ObjectOutputStream(baos) - oos.writeObject(value) - val encoded = Base64.encode(baos.toByteArray(), Base64.DEFAULT) - if (APILevel.require(9)) getPreferences(name).edit().putString(key, String(encoded)) - .apply() - else getPreferences(name).edit().putString(key, String(encoded)).commit() - } catch (e: IOException) { + val decoded = Base64.decode(value.toByteArray(), Base64.DEFAULT) + bais = ByteArrayInputStream(decoded) + ois = ObjectInputStream(bais) + result = ois.readObject() as C + } catch (e: Exception) { LogHelper.e(e) - throw RuntimeException(e) } finally { - if (oos != null) { + if (ois != null) { try { - oos.close() + ois.close() } catch (e: IOException) { LogHelper.e(e) } } - if (baos != null) { + if (bais != null) { try { - baos.close() + bais.close() } catch (e: IOException) { LogHelper.e(e) } @@ -217,21 +142,118 @@ open class PreferencesUtil { } } - - fun remove(key: String?) { - remove(defaultName, key) - } - - fun remove(name: String, key: String?) { - if (APILevel.require(9)) getPreferences(name).edit().remove(key).apply() - else getPreferences(name).edit().remove(key).commit() - } + return result + } - @JvmOverloads - fun clear(name: String = defaultName) { - if (APILevel.require(9)) getPreferences(name).edit().clear().apply() - else getPreferences(name).edit().clear().commit() + fun put(key: String?, value: Boolean) { + put(getDefaultPrefix(), key, value) + } + + fun put(key: String?, value: Int) { + put(getDefaultPrefix(), key, value) + } + + fun put(key: String?, value: Float) { + put(getDefaultPrefix(), key, value) + } + + fun put(key: String?, value: Long) { + put(getDefaultPrefix(), key, value) + } + + fun put(key: String?, value: String?) { + put(getDefaultPrefix(), key, value) + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + fun put(key: String?, value: Set?) { + put(getDefaultPrefix(), key, value) + } + + @TargetApi(Build.VERSION_CODES.FROYO) + fun put(key: String?, value: C) { + put(getDefaultPrefix(), key, value) + } + + fun put(name: String, key: String?, value: Boolean) { + if (APILevel.require(9)) getPreferences()?.edit()?.putBoolean(key, value)?.apply() + else getPreferences()?.edit()?.putBoolean(key, value)?.commit() + } + + fun put(name: String, key: String?, value: Int) { + if (APILevel.require(9)) getPreferences()?.edit()?.putInt(key, value)?.apply() + else getPreferences()?.edit()?.putInt(key, value)?.commit() + } + + fun put(name: String, key: String?, value: Float) { + if (APILevel.require(9)) getPreferences()?.edit()?.putFloat(key, value)?.apply() + else getPreferences()?.edit()?.putFloat(key, value)?.commit() + } + + fun put(name: String, key: String?, value: Long) { + if (APILevel.require(9)) getPreferences()?.edit()?.putLong(key, value)?.apply() + else getPreferences()?.edit()?.putLong(key, value)?.commit() + } + + fun put(name: String, key: String?, value: String?) { + if (APILevel.require(9)) getPreferences()?.edit()?.putString(key, value)?.apply() + else getPreferences()?.edit()?.putString(key, value)?.commit() + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + fun put(name: String, key: String?, value: Set?) { + if (APILevel.require(9)) getPreferences()?.edit()?.putStringSet(key, value)?.apply() + else getPreferences()?.edit()?.putStringSet(key, value)?.commit() + } + + @TargetApi(Build.VERSION_CODES.FROYO) + fun put(name: String, key: String?, value: C) { + var baos: ByteArrayOutputStream? = null + var oos: ObjectOutputStream? = null + + try { + baos = ByteArrayOutputStream() + oos = ObjectOutputStream(baos) + oos.writeObject(value) + val encoded = Base64.encode(baos.toByteArray(), Base64.DEFAULT) + if (APILevel.require(9)) getPreferences()?.edit()?.putString(key, String(encoded))?.apply() + else getPreferences()?.edit()?.putString(key, String(encoded))?.commit() + } catch (e: IOException) { + LogHelper.e(e) + throw RuntimeException(e) + } finally { + if (oos != null) { + try { + oos.close() + } catch (e: IOException) { + LogHelper.e(e) + } + } + if (baos != null) { + try { + baos.close() + } catch (e: IOException) { + LogHelper.e(e) + } + } } } -} \ No newline at end of file + + + fun remove(key: String?) { + remove(getDefaultPrefix(), key) + } + + fun remove(name: String, key: String?) { + if (APILevel.require(9)) getPreferences()?.edit()?.remove(key)?.apply() + else getPreferences()?.edit()?.remove(key)?.commit() + } + + + @JvmOverloads + fun clear(name: String = getDefaultPrefix()) { + if (APILevel.require(9)) getPreferences()?.edit()?.clear()?.apply() + else getPreferences()?.edit()?.clear()?.commit() + } +}