앱 서랍 검색/아이콘 로딩 속도 최적화 및 라이브 월페이퍼 배터리 소모 절감
- 앱 서랍 속도 최적화: - IconPackManager: LruCache 용량을 100 -> 300으로 확대하고 동기 조회 메서드(getCachedIcon) 추가 - AppsAdapter: 캐시 히트 시 코루틴/비동기 지연 없이 즉시 아이콘 바인딩하여 깜빡임 및 스크롤 지연 제거 - AppDrawerBottomSheet: fetchApps()에 세션 단위 메모리 캐시(실행 가능 앱, AppInfo, 연락처, 추천 앱)를 도입해 검색어 입력 시마다 반복되던 PackageManager IPC 및 Realm 재조회 제거 - 라이브 월페이퍼 배터리 최적화 (MyWallpaperService): - 화면 OFF/전환(!visible) 시 syncDelayMs 대기 없이 즉시 stopRendering() 호출 - 5초 주기 updateWeatherRunnable을 60초 주기로 완화하고 날씨 데이터가 비어 있고 비충전 시 루프 즉시 종료 - 미디어 전환 시마다 반복되던 loadFiles() 디스크/이미지 헤더 스캔을 5분 캐싱 - 기본 렌더링 프레임 간격(70ms -> 120ms) 및 페이지 전환 주기(8초 -> 15초) 상향으로 CPU 사용량 절감
This commit is contained in:
@@ -63,6 +63,12 @@ class AppDrawerBottomSheet : BottomSheetDialogFragment() {
|
||||
private var fetchJob: Job? = null
|
||||
private var isSpinnerInitialized = false
|
||||
|
||||
// 세션 내 재조회 방지를 위한 인메모리 캐시
|
||||
private var cachedLaunchablePackages: Set<String>? = null
|
||||
private var cachedAppsByKey: Pair<String, List<AppInfo>>? = null
|
||||
private var cachedAllContacts: List<SimpleContact>? = null
|
||||
private var cachedRecommendations: Pair<Boolean, List<RecommendationItem>>? = null
|
||||
|
||||
companion object {
|
||||
const val TAG = "AppDrawerBottomSheet"
|
||||
|
||||
@@ -382,33 +388,42 @@ class AppDrawerBottomSheet : BottomSheetDialogFragment() {
|
||||
val realm = WorkersDb.getRealm()
|
||||
val pm = context.packageManager
|
||||
|
||||
// 1. 런처에서 실행 가능한 전체 패키지 Set 확보 (단 1회 IPC)
|
||||
val mainIntent = Intent(Intent.ACTION_MAIN, null).apply {
|
||||
addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
// 1. 런처에서 실행 가능한 전체 패키지 Set 확보 (세션 내 1회 IPC 캐싱)
|
||||
val launchablePackages = cachedLaunchablePackages ?: run {
|
||||
val mainIntent = Intent(Intent.ACTION_MAIN, null).apply {
|
||||
addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
}
|
||||
pm.queryIntentActivities(mainIntent, 0)
|
||||
.mapNotNull { it.activityInfo?.packageName }
|
||||
.toHashSet()
|
||||
.also { cachedLaunchablePackages = it }
|
||||
}
|
||||
val launchablePackages = pm.queryIntentActivities(mainIntent, 0)
|
||||
.mapNotNull { it.activityInfo?.packageName }
|
||||
.toHashSet()
|
||||
|
||||
// 2. 추천 목록 먼저 계산 후 UI 선반영
|
||||
val scoredItems = WorkersDb.getContextualRecommendations(limit = 18)
|
||||
val unifiedList = mutableListOf<RecommendationItem>()
|
||||
|
||||
for (item in scoredItems) {
|
||||
if (item.type == "APP") {
|
||||
val app = realm.query<AppInfo>("pkgName == $0", item.key).first().find()
|
||||
if (app != null && (app.blockRecommend == false || (binding.hidden.isSelected == app.blockRecommend))) {
|
||||
if (launchablePackages.contains(app.pkgName)) {
|
||||
unifiedList.add(RecommendationItem.AppItem(realm.copyFromRealm(app)))
|
||||
// 2. 추천 목록 먼저 계산 후 UI 선반영 (세션 내 캐싱)
|
||||
val isHiddenSelected = binding.hidden.isSelected
|
||||
val unifiedList = cachedRecommendations
|
||||
?.takeIf { it.first == isHiddenSelected }
|
||||
?.second
|
||||
?: run {
|
||||
val scoredItems = WorkersDb.getContextualRecommendations(limit = 18)
|
||||
val list = mutableListOf<RecommendationItem>()
|
||||
for (item in scoredItems) {
|
||||
if (item.type == "APP") {
|
||||
val app = realm.query<AppInfo>("pkgName == $0", item.key).first().find()
|
||||
if (app != null && (app.blockRecommend == false || (isHiddenSelected == app.blockRecommend))) {
|
||||
if (launchablePackages.contains(app.pkgName)) {
|
||||
list.add(RecommendationItem.AppItem(realm.copyFromRealm(app)))
|
||||
}
|
||||
}
|
||||
} else if (item.type == "CONTACT") {
|
||||
val contact = realm.query<SimpleContact>("id == $0", item.key).first().find()
|
||||
if (contact != null) {
|
||||
list.add(RecommendationItem.ContactItem(realm.copyFromRealm(contact)))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (item.type == "CONTACT") {
|
||||
val contact = realm.query<SimpleContact>("id == $0", item.key).first().find()
|
||||
if (contact != null) {
|
||||
unifiedList.add(RecommendationItem.ContactItem(realm.copyFromRealm(contact)))
|
||||
}
|
||||
list.also { cachedRecommendations = isHiddenSelected to it }
|
||||
}
|
||||
}
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
if (_binding != null && unifiedList.isNotEmpty()) {
|
||||
@@ -417,24 +432,30 @@ class AppDrawerBottomSheet : BottomSheetDialogFragment() {
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 전체 앱 목록 쿼리 및 메모리 필터링
|
||||
val baseAppQuery = realm.query<AppInfo>()
|
||||
.sort("clickCount", Sort.DESCENDING)
|
||||
.sort("lastUseDate", Sort.DESCENDING)
|
||||
.find()
|
||||
// 3. 전체 앱 목록 쿼리 및 메모리 캐싱 (카테고리/숨김 상태별 캐시)
|
||||
val cacheKey = "${isHiddenSelected}_$currentCategoryKey"
|
||||
val scopedAppsList = cachedAppsByKey
|
||||
?.takeIf { it.first == cacheKey }
|
||||
?.second
|
||||
?: run {
|
||||
val baseAppQuery = realm.query<AppInfo>()
|
||||
.sort("clickCount", Sort.DESCENDING)
|
||||
.sort("lastUseDate", Sort.DESCENDING)
|
||||
.find()
|
||||
|
||||
val scopedAppsList = baseAppQuery.mapNotNull { app ->
|
||||
val pkg = app.pkgName ?: ""
|
||||
if (!launchablePackages.contains(pkg)) return@mapNotNull null
|
||||
baseAppQuery.mapNotNull { app ->
|
||||
val pkg = app.pkgName ?: ""
|
||||
if (!launchablePackages.contains(pkg)) return@mapNotNull null
|
||||
|
||||
val isVisible = binding.hidden.isSelected || (app.visibilityMode == 0)
|
||||
if (!isVisible) return@mapNotNull null
|
||||
val isVisible = isHiddenSelected || (app.visibilityMode == 0)
|
||||
if (!isVisible) return@mapNotNull null
|
||||
|
||||
val fixedCategory = CategoryManualMapper.getFixedCategory(pkg, app.appName, app.systemCategoryInt)
|
||||
if (currentCategoryKey != "ALL" && fixedCategory != currentCategoryKey) return@mapNotNull null
|
||||
val fixedCategory = CategoryManualMapper.getFixedCategory(pkg, app.appName, app.systemCategoryInt)
|
||||
if (currentCategoryKey != "ALL" && fixedCategory != currentCategoryKey) return@mapNotNull null
|
||||
|
||||
realm.copyFromRealm(app).apply { category = fixedCategory }
|
||||
}
|
||||
realm.copyFromRealm(app).apply { category = fixedCategory }
|
||||
}.also { cachedAppsByKey = cacheKey to it }
|
||||
}
|
||||
|
||||
val filteredApps = if (keyword.isNullOrEmpty()) {
|
||||
scopedAppsList
|
||||
@@ -458,18 +479,16 @@ class AppDrawerBottomSheet : BottomSheetDialogFragment() {
|
||||
.map { it.first }
|
||||
}
|
||||
|
||||
// 4. 연락처 목록 필터링 (검색어 없을 때는 상위 10건만 DB 조회)
|
||||
// 4. 연락처 목록 필터링 (세션 내 캐싱)
|
||||
val allContacts = cachedAllContacts ?: realm.query<SimpleContact>()
|
||||
.sort("touchCount", Sort.DESCENDING)
|
||||
.find()
|
||||
.map { realm.copyFromRealm(it) }
|
||||
.also { cachedAllContacts = it }
|
||||
|
||||
val filteredContacts: List<SimpleContact> = if (keyword.isNullOrEmpty()) {
|
||||
realm.query<SimpleContact>()
|
||||
.sort("touchCount", Sort.DESCENDING)
|
||||
.limit(10)
|
||||
.find()
|
||||
.map { realm.copyFromRealm(it) }
|
||||
allContacts.take(10)
|
||||
} else {
|
||||
val allContacts = realm.query<SimpleContact>()
|
||||
.sort("touchCount", Sort.DESCENDING)
|
||||
.find()
|
||||
.map { realm.copyFromRealm(it) }
|
||||
|
||||
val searchTerms = listOfNotNull(
|
||||
keyword,
|
||||
|
||||
@@ -130,13 +130,18 @@ internal class AppsDiffUtil(
|
||||
fun loadIconAsync(imageView: android.widget.ImageView, pkgName: String?) {
|
||||
if (pkgName == null) return
|
||||
|
||||
// 1. 이미지가 로딩되기 전 초기화 (재사용 뷰 깜빡임 방지)
|
||||
imageView.setImageDrawable(null)
|
||||
|
||||
// Tag를 사용하여 뷰홀더가 재사용되었을 때 이전 작업 취소 식별
|
||||
imageView.tag = pkgName
|
||||
|
||||
// CoroutineScope (lifecycleScope나 adapter 내부 scope 사용)
|
||||
// 1. 캐시 히트 시 코루틴/스레드 전환 없이 동기 즉시 반영 (깜빡임 및 지연 제거)
|
||||
IconPackManager.getCachedIcon(pkgName)?.let { cached ->
|
||||
imageView.setImageDrawable(cached)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 캐시 미스 시에만 초기화 후 IO 스레드에서 로딩
|
||||
imageView.setImageDrawable(null)
|
||||
|
||||
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
|
||||
val icon = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
IconPackManager.getDrawableIconForPackage(imageView.context, pkgName)
|
||||
|
||||
@@ -6,11 +6,12 @@ import android.util.LruCache // 이거 임포트
|
||||
|
||||
class IconPackManager {
|
||||
companion object {
|
||||
// [추가] 메모리 캐시 (최대 4MB 또는 아이콘 100개 분량 등 설정)
|
||||
private val iconCache = object : LruCache<String, Drawable>(100) {
|
||||
// 사이즈 측정 로직이 필요하면 sizeOf 오버라이드 (여기선 갯수 기준 100개)
|
||||
// 메모리 캐시 (아이콘 300개 분량으로 확대해 스크롤 시 IPC 미스 최소화)
|
||||
private val iconCache = object : LruCache<String, Drawable>(300) {
|
||||
}
|
||||
|
||||
fun getCachedIcon(packageName: String): Drawable? = iconCache.get(packageName)
|
||||
|
||||
fun getDrawableIconForPackage(context: Context, packageName: String): Drawable? {
|
||||
// 1. 캐시에 있는지 확인
|
||||
val cachedIcon = iconCache.get(packageName)
|
||||
|
||||
+25
-10
@@ -241,14 +241,15 @@ class MyWallpaperService : WallpaperService() {
|
||||
Log.w(TAG, "onVisibilityChanged: Renderer was null. Re-initializing.")
|
||||
initializeRenderer()
|
||||
}
|
||||
requestSyncRenderState()
|
||||
|
||||
if (visible) {
|
||||
requestSyncRenderState()
|
||||
// 화면이 켜지면 즉시 업데이트하고 타이머 시작
|
||||
handler.removeCallbacks(updateWeatherRunnable)
|
||||
handler.post(updateWeatherRunnable)
|
||||
} else {
|
||||
// 화면이 꺼지면 타이머 중지
|
||||
// 화면이 꺼지면 대기 없이 즉시 렌더링 및 타이머 중지
|
||||
handler.removeCallbacks(syncRenderStateRunnable)
|
||||
handler.post { stopRendering() }
|
||||
handler.removeCallbacks(updateWeatherRunnable)
|
||||
}
|
||||
|
||||
@@ -311,11 +312,11 @@ class MyWallpaperService : WallpaperService() {
|
||||
nativeRenderer = NativeRenderer()
|
||||
nativeRenderer?.initialize() // nativeInit() -> initialize()
|
||||
nativeRenderer?.setFadeDuration(3000)
|
||||
nativeRenderer?.setTurnPageDuration(8000)
|
||||
nativeRenderer?.setTurnPageDuration(15000)
|
||||
nativeRenderer?.setAnimationMode(NativeRenderer.ANIMATION_MODE_PAN)
|
||||
nativeRenderer?.setTransitionMode(NativeRenderer.TRANSITION_MODE_FADE)
|
||||
nativeRenderer?.setAnimationSpeed(1.0f)
|
||||
nativeRenderer?.setImageRenderFrame(70)
|
||||
nativeRenderer?.setImageRenderFrame(120)
|
||||
NativeRenderer.nativeSetNextMediaCallback(nextMediaCallback)
|
||||
|
||||
|
||||
@@ -345,7 +346,15 @@ class MyWallpaperService : WallpaperService() {
|
||||
}
|
||||
}
|
||||
|
||||
private var lastFilesScanTime = 0L
|
||||
|
||||
fun loadFiles() {
|
||||
val now = System.currentTimeMillis()
|
||||
if (mediaFiles.isNotEmpty() && now - lastFilesScanTime < 5 * 60 * 1000L) {
|
||||
return
|
||||
}
|
||||
lastFilesScanTime = now
|
||||
|
||||
if (!mediaDir.exists()) mediaDir.mkdirs()
|
||||
|
||||
val allFiles = mediaDir.listFiles()?.filter { supportedExtensions.contains(it.extension.lowercase()) } ?: return
|
||||
@@ -703,10 +712,11 @@ class MyWallpaperService : WallpaperService() {
|
||||
var nextDelay = 30000L // 기본 20초
|
||||
|
||||
if (isCharging) {
|
||||
nextDelay = 5000L // 충전 중이거나 70% 이상이면 10초
|
||||
nativeRenderer?.setImageRenderFrame(45)
|
||||
nextDelay = 60_000L // 충전 중에는 60초 간격
|
||||
nativeRenderer?.setImageRenderFrame(66)
|
||||
} else if (batteryLevel >= 80) {
|
||||
nativeRenderer?.setImageRenderFrame(70)
|
||||
nextDelay = 60_000L
|
||||
nativeRenderer?.setImageRenderFrame(120)
|
||||
} else {
|
||||
handler.removeCallbacks(this)
|
||||
return
|
||||
@@ -714,6 +724,10 @@ class MyWallpaperService : WallpaperService() {
|
||||
|
||||
// 비트맵 생성 및 전달
|
||||
val weather = weatherSummaryProvider()
|
||||
if (weather.isEmpty() && !isCharging) {
|
||||
handler.removeCallbacks(this)
|
||||
return
|
||||
}
|
||||
val bitmap = drawBitmapFromText(weather,isCharging)
|
||||
bitmap?.let {
|
||||
nativeRenderer?.setWeatherBitmap(it)
|
||||
@@ -742,6 +756,7 @@ class MyWallpaperService : WallpaperService() {
|
||||
private val nextMediaCallback = object : NativeRenderer.NextMediaCallback {
|
||||
override fun onNextMediaRequested() {
|
||||
loadFiles()
|
||||
if (mediaFiles.isEmpty()) return
|
||||
val nextFile = mediaFiles.random()
|
||||
Log.d(TAG, "Callback: Preloading next random media: ${nextFile.absolutePath}")
|
||||
// ⑥ 명언 (DB 랜덤 추출)
|
||||
@@ -764,10 +779,10 @@ class MyWallpaperService : WallpaperService() {
|
||||
if (batteryLevel >= 70 || isCharging) {
|
||||
val bitmap = drawBitmapFromText(weatherSummaryProvider())
|
||||
bitmap?.let { nativeRenderer?.setWeatherBitmap(it) }
|
||||
nativeRenderer?.setImageRenderFrame(55)
|
||||
nativeRenderer?.setImageRenderFrame(80)
|
||||
Log.d(TAG, "Battery Low: Weather updated only on media change.")
|
||||
} else {
|
||||
nativeRenderer?.setImageRenderFrame(99)
|
||||
nativeRenderer?.setImageRenderFrame(120)
|
||||
nativeRenderer?.setWeatherBitmap(null)
|
||||
}
|
||||
if (isCharging || batteryLevel > 90) {
|
||||
|
||||
Reference in New Issue
Block a user