This commit is contained in:
lunaticbum 2024-11-15 16:06:08 +09:00
parent 8ba7005c53
commit b81e12c61b
17 changed files with 448 additions and 428 deletions

View File

@ -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")

View File

@ -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<RecentSmsGetter>(PrefHelper.longTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<RecentSmsGetter>(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<RecentCallGetter>(PrefHelper.longTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<RecentCallGetter>(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<NewsFeedsGetter>(PrefHelper.shortTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<NewsFeedsGetter>(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<YoutubeGetter>(PrefHelper.longTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<YoutubeGetter>(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<RedditGetter>(PrefHelper.midTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<RedditGetter>(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<FmKoreaGetter>(PrefHelper.midTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<FmKoreaGetter>(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<DotaxGetter>(PrefHelper.midTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<DotaxGetter>(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<ClienGetter>(PrefHelper.midTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<ClienGetter>(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<DCGetter>(PrefHelper.midTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<DCGetter>(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<RuliWebGetter>(PrefHelper.midTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<RuliWebGetter>(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<TheQooGetter>(PrefHelper.midTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<TheQooGetter>(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<ArcaGetter>(PrefHelper.midTimePeriod, TimeUnit.MINUTES)
PeriodicWorkRequestBuilder<ArcaGetter>(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<LocationGetter>(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<LocationGetter>(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))
}
}

View File

@ -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)

View File

@ -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" ->{

View File

@ -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 클라이언트 객체 생성

View File

@ -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<String> {
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<Long> {
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<Boolean> {
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 -> {}
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
}
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
}
object PrefHelper : PreferencesHelper() {
override fun getDefaultPrefix(): String { return "rasel.lunar.launcher.helpers" }
override fun getSettings() : Map<String,Any> {
var jsonObj = HashMap<String,Any>()
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
}
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
override fun putSetting(json : Map<String,Any>) {
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) {

View File

@ -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 -> {

View File

@ -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<RssDataInterface> {
var returnList = mutableListOf<RssDataInterface>()
@ -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 {
var date = ""
try {
parser.require(XmlPullParser.START_TAG, null, "pubDate")
val date = readText(parser)
date = readText(parser)
parser.require(XmlPullParser.END_TAG, null, "pubDate")
} catch (e : Exception) {
}
return date
}

View File

@ -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()}]분 마다]"
})

View File

@ -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()
}
}
}

View File

@ -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())

View File

@ -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)
}
}

View File

@ -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

View File

@ -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())

View File

@ -1,49 +1,59 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/twelve">
<CheckBox
android:id="@+id/useDateTime"
android:text="USE DateTimeView"
android:textColor="@color/white"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<bums.lunatic.launcher.view.DateTimeView
android:id="@+id/previewDateTime"
app:layout_constraintTop_toBottomOf="@+id/useDateTime"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_width="0dp"
android:layout_height="60dp"/>
<com.google.android.material.textview.MaterialTextView
android:id="@+id/timeFormat"
android:id="@+id/timeDateTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/time_format"
android:text="date, time format"
android:textSize="@dimen/normalText"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
app:layout_constraintTop_toBottomOf="@id/previewDateTime"/>
<com.google.android.material.chip.ChipGroup
android:id="@+id/timeGroup"
android:layout_width="wrap_content"
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/timeFormatParent"
android:layout_width="@dimen/twoSeventySix"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/twelve"
android:hint="@string/time_format"
app:endIconMode="clear_text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/timeFormat"
app:selectionRequired="true"
app:singleSelection="true">
app:layout_constraintTop_toBottomOf="@+id/timeDateTitle">
<com.google.android.material.chip.Chip
android:id="@+id/selectTwelve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/twelve"
style="@style/Widget.Material3.Chip.Filter.Elevated" />
<com.google.android.material.chip.Chip
android:id="@+id/followSystemTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/follow_system"
style="@style/Widget.Material3.Chip.Filter.Elevated" />
<com.google.android.material.chip.Chip
android:id="@+id/selectTwentyFour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/twenty_four"
style="@style/Widget.Material3.Chip.Filter.Elevated" />
</com.google.android.material.chip.ChipGroup>
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/timeFormat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:imeOptions="actionDone"
android:singleLine="true" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/dateFormatParent"
@ -54,7 +64,7 @@
app:endIconMode="clear_text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/timeGroup">
app:layout_constraintTop_toBottomOf="@+id/timeFormatParent">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/dateFormat"
@ -64,4 +74,5 @@
android:imeOptions="actionDone"
android:singleLine="true" />
</com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@ -1,9 +0,0 @@
package kr.lunaticbum.utils.preferences;
/**
* Pref is abbreviation class of {@link PreferencesUtil}.
*
* @author Robin Gustafsson
*/
public class Pref extends PreferencesUtil {
}

View File

@ -15,74 +15,98 @@ 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)
interface PrefKey<T> {
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<String,Any>
fun putSetting(json : Map<String,Any>)
}
abstract class PreferencesHelper : PrefJsonConvert {
var sharedPreferences : SharedPreferences? = null
open fun allPrefKeys() : ArrayList<String> =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<String,Any>
abstract override fun putSetting(json : Map<String,Any>)
private val LogHelper = LogHelper(PreferencesHelper::class.java)
override fun initialize(context: Context) {
inject(context.getSharedPreferences(getDefaultPrefix(), Context.MODE_PRIVATE))
}
override fun inject(sharedPreferences : SharedPreferences) {
this.sharedPreferences = sharedPreferences
}
fun get(key: String?, defValue: Boolean): Boolean {
return get(defaultName, key, defValue)
return get(getDefaultPrefix(), key, defValue)
}
fun get(key: String?, defValue: Int): Int {
return get(defaultName, key, defValue)
return get(getDefaultPrefix(), key, defValue)
}
fun get(key: String?, defValue: Float): Float {
return get(defaultName, key, defValue)
return get(getDefaultPrefix(), key, defValue)
}
fun get(key: String?, defValue: Long): Long {
return get(defaultName, key, defValue)
return get(getDefaultPrefix(), key, defValue)
}
fun get(key: String?, defValue: String?): String? {
return get(defaultName, key, defValue)
return get(getDefaultPrefix(), key, defValue)
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
fun get(key: String?, defValue: Set<String?>?): Set<String>? {
return get(defaultName, key, defValue)
return get(getDefaultPrefix(), key, defValue)
}
@TargetApi(Build.VERSION_CODES.FROYO)
fun <C : Serializable?> get(key: String?, defValue: C): C {
return get(defaultName, key, defValue)
return get(getDefaultPrefix(), key, defValue)
}
fun get(name: String, key: String?, defValue: Boolean): Boolean {
return getPreferences(name).getBoolean(key, defValue)
return getPreferences()?.getBoolean(key, defValue) ?: false
}
fun getPreferences(): SharedPreferences? {
return this.sharedPreferences
}
fun get(name: String, key: String?, defValue: Int): Int {
return getPreferences(name).getInt(key, defValue)
return getPreferences()?.getInt(key, defValue) ?: 0
}
fun get(name: String, key: String?, defValue: Float): Float {
return getPreferences(name).getFloat(key, defValue)
return getPreferences()?.getFloat(key, defValue) ?: 0f
}
fun get(name: String, key: String?, defValue: Long): Long {
return getPreferences(name).getLong(key, defValue)
return getPreferences()?.getLong(key, defValue) ?: 0L
}
fun get(name: String, key: String?, defValue: String?): String? {
return getPreferences(name).getString(key, defValue)
return getPreferences()?.getString(key, defValue)
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
fun get(name: String, key: String?, defValue: Set<String?>?): Set<String>? {
return getPreferences(name).getStringSet(key, defValue)
return getPreferences()?.getStringSet(key, defValue)
}
@TargetApi(Build.VERSION_CODES.FROYO)
@ -91,7 +115,7 @@ open class PreferencesUtil {
var ois: ObjectInputStream? = null
var result = defValue
val value = getPreferences(name).getString(key, null)
val value = getPreferences()?.getString(key, null)
if (value != null) {
try {
val decoded = Base64.decode(value.toByteArray(), Base64.DEFAULT)
@ -123,64 +147,64 @@ open class PreferencesUtil {
fun put(key: String?, value: Boolean) {
put(defaultName, key, value)
put(getDefaultPrefix(), key, value)
}
fun put(key: String?, value: Int) {
put(defaultName, key, value)
put(getDefaultPrefix(), key, value)
}
fun put(key: String?, value: Float) {
put(defaultName, key, value)
put(getDefaultPrefix(), key, value)
}
fun put(key: String?, value: Long) {
put(defaultName, key, value)
put(getDefaultPrefix(), key, value)
}
fun put(key: String?, value: String?) {
put(defaultName, key, value)
put(getDefaultPrefix(), key, value)
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
fun put(key: String?, value: Set<String?>?) {
put(defaultName, key, value)
put(getDefaultPrefix(), key, value)
}
@TargetApi(Build.VERSION_CODES.FROYO)
fun <C : Serializable?> put(key: String?, value: C) {
put(defaultName, key, value)
put(getDefaultPrefix(), key, value)
}
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()
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(name).edit().putInt(key, value).apply()
else getPreferences(name).edit().putInt(key, value).commit()
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(name).edit().putFloat(key, value).apply()
else getPreferences(name).edit().putFloat(key, value).commit()
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(name).edit().putLong(key, value).apply()
else getPreferences(name).edit().putLong(key, value).commit()
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(name).edit().putString(key, value).apply()
else getPreferences(name).edit().putString(key, value).commit()
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<String?>?) {
if (APILevel.require(9)) getPreferences(name).edit().putStringSet(key, value).apply()
else getPreferences(name).edit().putStringSet(key, value).commit()
if (APILevel.require(9)) getPreferences()?.edit()?.putStringSet(key, value)?.apply()
else getPreferences()?.edit()?.putStringSet(key, value)?.commit()
}
@TargetApi(Build.VERSION_CODES.FROYO)
@ -193,9 +217,8 @@ open class PreferencesUtil {
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()
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)
@ -219,19 +242,18 @@ open class PreferencesUtil {
fun remove(key: String?) {
remove(defaultName, key)
remove(getDefaultPrefix(), key)
}
fun remove(name: String, key: String?) {
if (APILevel.require(9)) getPreferences(name).edit().remove(key).apply()
else getPreferences(name).edit().remove(key).commit()
if (APILevel.require(9)) getPreferences()?.edit()?.remove(key)?.apply()
else getPreferences()?.edit()?.remove(key)?.commit()
}
@JvmOverloads
fun clear(name: String = defaultName) {
if (APILevel.require(9)) getPreferences(name).edit().clear().apply()
else getPreferences(name).edit().clear().commit()
}
fun clear(name: String = getDefaultPrefix()) {
if (APILevel.require(9)) getPreferences()?.edit()?.clear()?.apply()
else getPreferences()?.edit()?.clear()?.commit()
}
}