diff --git a/app/src/main/kotlin/bums/lunatic/launcher/LauncherActivity.kt b/app/src/main/kotlin/bums/lunatic/launcher/LauncherActivity.kt index 42e2df20..5b6cc2c3 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/LauncherActivity.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/LauncherActivity.kt @@ -22,6 +22,7 @@ import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper +import androidx.lifecycle.lifecycleScope import android.provider.OpenableColumns import android.provider.Settings import android.view.GestureDetector @@ -1076,7 +1077,10 @@ open class LauncherActivity : CommonActivity() { super.onResume() Blog.LOGE("LauncherActivity onResume") if (checkUsageStatsPermission()) { - WorkersDb.syncSystemUsageStats(applicationContext) + val appCtx = applicationContext + lifecycleScope.launch(Dispatchers.IO) { + WorkersDb.syncSystemUsageStats(appCtx) + } } else { requestPermission() } diff --git a/core/core-database/src/main/kotlin/bums/lunatic/launcher/workers/WorkersDb.kt b/core/core-database/src/main/kotlin/bums/lunatic/launcher/workers/WorkersDb.kt index f5b8ebe8..cff3ec72 100644 --- a/core/core-database/src/main/kotlin/bums/lunatic/launcher/workers/WorkersDb.kt +++ b/core/core-database/src/main/kotlin/bums/lunatic/launcher/workers/WorkersDb.kt @@ -391,7 +391,14 @@ object WorkersDb { } } + @Volatile + private var lastUsageSyncTime = 0L + fun syncSystemUsageStats(context: Context) { + val now = System.currentTimeMillis() + if (now - lastUsageSyncTime < 3 * 60 * 1000L) return + lastUsageSyncTime = now + val usm = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager val calendar = Calendar.getInstance() val endTime = calendar.timeInMillis @@ -409,12 +416,13 @@ object WorkersDb { val realm = getRealm() // WorkersDb의 getRealm() 활용 realm.writeBlocking { + val appInfoMap = query().find().associateBy { it.pkgName } for (stats in usageStatsList) { val pkgName = stats.packageName val lastUsedTime = stats.lastTimeUsed // 2. 우리 DB(AppInfo)에 저장된 시간보다 최신인지 확인 - val appInfo = query("pkgName == $0", pkgName).first().find() + val appInfo = appInfoMap[pkgName] if (appInfo != null) { // 시스템 기록이 내 DB 기록보다 더 최신이면 -> 런처 밖에서 실행된 것임!