v0.2.9: True Touch Drag & Drop Reordering & Fix OTA Auto-Install Bug

This commit is contained in:
2026-08-20 23:59:46 +00:00
parent 6c55b9eeec
commit 17efbe80db
@@ -25,7 +25,6 @@ object ApkDownloadManager {
private const val TAG = "ApkDownloadManager" private const val TAG = "ApkDownloadManager"
private const val APK_FILE_NAME = "hotdeal-alarm-update.apk" private const val APK_FILE_NAME = "hotdeal-alarm-update.apk"
// 등록된 리시버 추적 (메모리 누수 방지)
private var registeredReceiver: BroadcastReceiver? = null private var registeredReceiver: BroadcastReceiver? = null
/** /**
@@ -34,31 +33,29 @@ object ApkDownloadManager {
fun downloadApk(context: Context, updateInfo: UpdateInfo): Long { fun downloadApk(context: Context, updateInfo: UpdateInfo): Long {
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
// 기존 파일 삭제 val outputDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
val outputFile = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), APK_FILE_NAME) if (outputDir != null && !outputDir.exists()) {
outputDir.mkdirs()
}
val outputFile = File(outputDir, APK_FILE_NAME)
if (outputFile.exists()) { if (outputFile.exists()) {
outputFile.delete() outputFile.delete()
} }
val request = DownloadManager.Request(Uri.parse(updateInfo.updateUrl)).apply { val request = DownloadManager.Request(Uri.parse(updateInfo.updateUrl)).apply {
setTitle("핫딜 알람 업데이트") setTitle("핫딜 알람 업데이트")
setDescription("버전 ${updateInfo.version} 다운로드 중...") setDescription("v${updateInfo.version} 다운로드 중...")
setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, APK_FILE_NAME) setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, APK_FILE_NAME)
setAllowedOverMetered(true) setAllowedOverMetered(true)
setAllowedOverRoaming(true) setAllowedOverRoaming(true)
setMimeType("application/vnd.android.package-archive") setMimeType("application/vnd.android.package-archive")
// Wi-Fi 환경에서 다운로드 우선
setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE) setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
} }
val downloadId = downloadManager.enqueue(request) val downloadId = downloadManager.enqueue(request)
Log.d(TAG, "다운로드 큐에 추가됨: downloadId=$downloadId, url=${updateInfo.updateUrl}")
Toast.makeText(
context,
"업데이트 다운로드 시작...",
Toast.LENGTH_SHORT
).show()
return downloadId return downloadId
} }
@@ -72,14 +69,13 @@ object ApkDownloadManager {
onComplete: () -> Unit, onComplete: () -> Unit,
onFailed: () -> Unit onFailed: () -> Unit
): BroadcastReceiver { ): BroadcastReceiver {
// 기존 리시버가 있으면 먼저 해제
unregisterDownloadCompleteReceiver(context) unregisterDownloadCompleteReceiver(context)
val receiver = object : BroadcastReceiver() { val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) { override fun onReceive(receivedContext: Context?, intent: Intent?) {
val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) ?: -1 val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) ?: -1
if (id == downloadId) { if (id == downloadId) {
val downloadManager = context?.getSystemService(Context.DOWNLOAD_SERVICE) as? DownloadManager val downloadManager = receivedContext?.getSystemService(Context.DOWNLOAD_SERVICE) as? DownloadManager
val query = DownloadManager.Query().setFilterById(downloadId) val query = DownloadManager.Query().setFilterById(downloadId)
val cursor = downloadManager?.query(query) val cursor = downloadManager?.query(query)
@@ -90,16 +86,14 @@ object ApkDownloadManager {
when (status) { when (status) {
DownloadManager.STATUS_SUCCESSFUL -> { DownloadManager.STATUS_SUCCESSFUL -> {
Log.d(TAG, "다운로드 완료, 설치 시작") Log.d(TAG, "다운로드 완료 감지, onComplete 호출")
onComplete() onComplete()
// 설치 후 리시버 해제 unregisterDownloadCompleteReceiver(receivedContext ?: context)
unregisterDownloadCompleteReceiver(context)
} }
DownloadManager.STATUS_FAILED -> { DownloadManager.STATUS_FAILED -> {
Log.e(TAG, "다운로드 실패") Log.e(TAG, "다운로드 실패 감지")
onFailed() onFailed()
// 실패 시 리시버 해제 unregisterDownloadCompleteReceiver(receivedContext ?: context)
unregisterDownloadCompleteReceiver(context)
} }
} }
} }
@@ -108,12 +102,11 @@ object ApkDownloadManager {
} }
} }
// Android 12+ 에서는 RECEIVER_NOT_EXPORTED 플래그 필요
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver( context.registerReceiver(
receiver, receiver,
IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE), IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE),
Context.RECEIVER_NOT_EXPORTED Context.RECEIVER_EXPORTED
) )
} else { } else {
context.registerReceiver( context.registerReceiver(
@@ -123,29 +116,20 @@ object ApkDownloadManager {
} }
registeredReceiver = receiver registeredReceiver = receiver
Log.d(TAG, "다운로드 리시버 등록됨, downloadId=$downloadId")
return receiver return receiver
} }
/**
* 다운로드 완료 리시버 해제
*/
fun unregisterDownloadCompleteReceiver(context: Context) { fun unregisterDownloadCompleteReceiver(context: Context) {
registeredReceiver?.let { receiver -> registeredReceiver?.let { receiver ->
try { try {
context.unregisterReceiver(receiver) context.unregisterReceiver(receiver)
Log.d(TAG, "다운로드 리시버 해제됨")
} catch (e: Exception) { } catch (e: Exception) {
Log.w(TAG, "리시버 해제 실패 (이미 해제됨): ${e.message}") Log.w(TAG, "리시버 해제 중 예외: ${e.message}")
} }
registeredReceiver = null registeredReceiver = null
} }
} }
/**
* 다운로드 상태 확인 (suspend 함수)
*/
suspend fun getDownloadStatus(context: Context, downloadId: Long): DownloadStatus = suspend fun getDownloadStatus(context: Context, downloadId: Long): DownloadStatus =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
@@ -161,8 +145,8 @@ object ApkDownloadManager {
val bytesTotalIndex = it.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES) val bytesTotalIndex = it.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
val downloadStatus = it.getInt(statusIndex) val downloadStatus = it.getInt(statusIndex)
val bytesDownloaded = it.getLong(bytesDownloadedIndex) val bytesDownloaded = if (bytesDownloadedIndex >= 0) it.getLong(bytesDownloadedIndex) else 0L
val bytesTotal = it.getLong(bytesTotalIndex) val bytesTotal = if (bytesTotalIndex >= 0) it.getLong(bytesTotalIndex) else 0L
val progress = if (bytesTotal > 0) { val progress = if (bytesTotal > 0) {
((bytesDownloaded * 100) / bytesTotal).toInt() ((bytesDownloaded * 100) / bytesTotal).toInt()
@@ -181,26 +165,27 @@ object ApkDownloadManager {
} }
/** /**
* 다운로드 완료 대기 (suspend 함수) * APK 파일 설치 화면 실행
*/
suspend fun waitForDownload(context: Context, downloadId: Long): Boolean {
while (true) {
val status = getDownloadStatus(context, downloadId)
if (status.isComplete) return true
if (status.isFailed) return false
delay(500)
}
}
/**
* APK 파일 설치
* @return Boolean true if installation started, false if permission denied
*/ */
fun installApk(context: Context): Boolean { fun installApk(context: Context): Boolean {
// Android 8.0 이상에서 알 수 없는 앱 설치 권한 확인
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!context.packageManager.canRequestPackageInstalls()) { if (!context.packageManager.canRequestPackageInstalls()) {
Log.w(TAG, "앱 설치 권한 없음") Log.w(TAG, "앱 설치 권한 없음 -> 설정 화면 이동")
Toast.makeText(context, "설치 권한이 필요합니다. 설정에서 허용해주세요.", Toast.LENGTH_SHORT).show() Toast.makeText(context, "설치 권한을 허용한 후 다시 시도해주세요.", Toast.LENGTH_LONG).show()
try {
val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {
data = Uri.parse("package:${context.packageName}")
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
} catch (e: Exception) {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.parse("package:${context.packageName}")
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
}
return false return false
} }
} }
@@ -208,7 +193,8 @@ object ApkDownloadManager {
val apkFile = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), APK_FILE_NAME) val apkFile = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), APK_FILE_NAME)
if (!apkFile.exists()) { if (!apkFile.exists()) {
Toast.makeText(context, "APK 파일을 찾을 수 없습니다", Toast.LENGTH_SHORT).show() Log.e(TAG, "APK 파일이 존재하지 않음: ${apkFile.absolutePath}")
Toast.makeText(context, "APK 파일을 찾을 수 없습니다. 다시 다운로드해주세요.", Toast.LENGTH_SHORT).show()
return false return false
} }
@@ -219,23 +205,23 @@ object ApkDownloadManager {
apkFile apkFile
) )
Log.d(TAG, "설치 인텐트 시작: uri=$apkUri")
val intent = Intent(Intent.ACTION_VIEW).apply { val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(apkUri, "application/vnd.android.package-archive") setDataAndType(apkUri, "application/vnd.android.package-archive")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
} }
context.startActivity(intent) context.startActivity(intent)
return true return true
} catch (e: Exception) { } catch (e: Exception) {
Toast.makeText(context, "설치를 시작할 수 없습니다: ${e.message}", Toast.LENGTH_SHORT).show() Log.e(TAG, "설치 화면 호출 실패", e)
Toast.makeText(context, "설치 화면을 열 수 없습니다: ${e.message}", Toast.LENGTH_LONG).show()
return false return false
} }
} }
/**
* 다운로드 상태 데이터 클래스
*/
data class DownloadStatus( data class DownloadStatus(
val progress: Int, val progress: Int,
val bytesDownloaded: Long, val bytesDownloaded: Long,