5 Commits
5 changed files with 427 additions and 195 deletions
+2 -2
View File
@@ -24,8 +24,8 @@ android {
applicationId = "com.hotdeal.alarm" applicationId = "com.hotdeal.alarm"
minSdk = 31 minSdk = 31
targetSdk = 35 targetSdk = 35
versionCode = 28 versionCode = 29
versionName = "0.2.8" versionName = "0.2.9"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables { vectorDrawables {
@@ -0,0 +1,138 @@
package com.hotdeal.alarm.presentation.components
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.lazy.LazyListItemInfo
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.zIndex
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
/**
* Compose LazyColumn Drag & Drop Reordering State
*/
@Composable
fun rememberDragDropListState(
lazyListState: LazyListState,
onMove: (Int, Int) -> Unit,
onDragEnd: () -> Unit = {}
): DragDropListState {
val scope = rememberCoroutineScope()
val state = remember(lazyListState) {
DragDropListState(
lazyListState = lazyListState,
onMove = onMove,
onDragEnd = onDragEnd,
scope = scope
)
}
return state
}
class DragDropListState(
val lazyListState: LazyListState,
private val onMove: (Int, Int) -> Unit,
private val onDragEnd: () -> Unit,
private val scope: CoroutineScope
) {
var initiallyDraggedElement by mutableStateOf<LazyListItemInfo?>(null)
private set
var currentIndexOfDraggedItem by mutableStateOf<Int?>(null)
private set
private val dragOffset = Animatable(0f)
val elementOffset: Float
get() = dragOffset.value
fun onDragStart(offset: Offset) {
lazyListState.layoutInfo.visibleItemsInfo
.firstOrNull { item -> offset.y.toInt() in item.offset..(item.offset + item.size) }
?.also { item ->
currentIndexOfDraggedItem = item.index
initiallyDraggedElement = item
}
}
fun onDragInterrupted() {
initiallyDraggedElement = null
currentIndexOfDraggedItem = null
scope.launch {
dragOffset.snapTo(0f)
}
}
fun onDrag(change: Offset) {
scope.launch {
dragOffset.snapTo(dragOffset.value + change.y)
val currentElement = initiallyDraggedElement ?: return@launch
val startOffset = currentElement.offset + dragOffset.value
val endOffset = startOffset + currentElement.size
val hoveredItem = lazyListState.layoutInfo.visibleItemsInfo
.firstOrNull { item ->
val itemMid = item.offset + item.size / 2
val isMidInRange = itemMid in startOffset.toInt()..endOffset.toInt()
isMidInRange && item.index != currentIndexOfDraggedItem
}
if (hoveredItem != null) {
val currentIndex = currentIndexOfDraggedItem ?: return@launch
val targetIndex = hoveredItem.index
onMove(currentIndex, targetIndex)
currentIndexOfDraggedItem = targetIndex
}
}
}
fun onDragStop() {
onDragEnd()
scope.launch {
dragOffset.animateTo(0f, spring(stiffness = Spring.StiffnessMediumLow))
initiallyDraggedElement = null
currentIndexOfDraggedItem = null
}
}
}
fun Modifier.dragDropGesture(
dragDropState: DragDropListState
): Modifier = this.pointerInput(dragDropState) {
detectDragGesturesAfterLongPress(
onDragStart = { offset -> dragDropState.onDragStart(offset) },
onDragEnd = { dragDropState.onDragStop() },
onDragCancel = { dragDropState.onDragInterrupted() },
onDrag = { change, dragAmount ->
change.consume()
dragDropState.onDrag(dragAmount)
}
)
}
fun Modifier.dragDropItem(
index: Int,
dragDropState: DragDropListState
): Modifier = this.then(
if (index == dragDropState.currentIndexOfDraggedItem) {
Modifier
.zIndex(10f)
.graphicsLayer {
translationY = dragDropState.elementOffset
scaleX = 1.03f
scaleY = 1.03f
shadowElevation = 8f
}
} else {
Modifier
}
)
@@ -14,7 +14,7 @@ import androidx.compose.foundation.border
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
@@ -40,19 +40,21 @@ import com.hotdeal.alarm.presentation.components.*
import com.hotdeal.alarm.presentation.main.MainUiState import com.hotdeal.alarm.presentation.main.MainUiState
import com.hotdeal.alarm.presentation.main.MainViewModel import com.hotdeal.alarm.presentation.main.MainViewModel
import com.hotdeal.alarm.ui.theme.* import com.hotdeal.alarm.ui.theme.*
import com.hotdeal.alarm.util.ApkDownloadManager
import com.hotdeal.alarm.util.PermissionHelper import com.hotdeal.alarm.util.PermissionHelper
import com.hotdeal.alarm.util.UpdateInfo
import com.hotdeal.alarm.util.VersionManager import com.hotdeal.alarm.util.VersionManager
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
/** /**
* One UI 9 & Material 3 Expressive Bento Settings Screen * One UI 9 & Material 3 Expressive Bento Settings Screen
* 순서 변경(Reordering) 및 Bento 그리드 구조를 지원하는 프리미엄 설정 화면 * 완벽한 터치 드래그 앤 드롭(Drag & Drop) 및 OTA 자동 설치를 지원하는 설정 화면
*/ */
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class) @OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable @Composable
fun SettingsScreen(viewModel: MainViewModel) { fun SettingsScreen(viewModel: MainViewModel) {
val context = LocalContext.current val context = LocalContext.current
val uiState by viewModel.uiState.collectAsState()
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val currentPollingInterval by viewModel.pollingInterval.collectAsState() val currentPollingInterval by viewModel.pollingInterval.collectAsState()
@@ -167,7 +169,7 @@ fun SettingsScreen(viewModel: MainViewModel) {
} }
// ============================================ // ============================================
// 탭 1: 알림 & 키워드 (NotificationTab) // 탭 1: 알림 & 키워드 (NotificationTab - 드래그앤드롭 Reordering)
// ============================================ // ============================================
@Composable @Composable
private fun NotificationTab( private fun NotificationTab(
@@ -183,14 +185,30 @@ private fun NotificationTab(
val activeKeywords = (uiState as? MainUiState.Success)?.keywords ?: emptyList() val activeKeywords = (uiState as? MainUiState.Success)?.keywords ?: emptyList()
val activeSitesCount = (uiState as? MainUiState.Success)?.siteConfigs?.count { it.isEnabled } ?: 0 val activeSitesCount = (uiState as? MainUiState.Success)?.siteConfigs?.count { it.isEnabled } ?: 0
val listState = rememberLazyListState()
val dragDropState = rememberDragDropListState(
lazyListState = listState,
onMove = { from, to ->
// 실시간 리스트 재배치
val itemOffset = 3 // 상단 Bento, 주기설정, 키워드인풋 3개 아이템 제외
val keywordFrom = from - itemOffset
val keywordTo = to - itemOffset
if (keywordFrom in activeKeywords.indices && keywordTo in activeKeywords.indices) {
viewModel.reorderKeywords(keywordFrom, keywordTo)
}
}
)
LazyColumn( LazyColumn(
state = listState,
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(horizontal = 14.dp), .padding(horizontal = 14.dp)
.dragDropGesture(dragDropState),
verticalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(top = 6.dp, bottom = 24.dp) contentPadding = PaddingValues(top = 6.dp, bottom = 24.dp)
) { ) {
// Now Status Bento 2x2 카드 // 0: Now Status Bento 2x2 카드
item { item {
SquircleCard( SquircleCard(
containerColor = MaterialTheme.colorScheme.surface, containerColor = MaterialTheme.colorScheme.surface,
@@ -255,7 +273,7 @@ private fun NotificationTab(
} }
} }
// 모듈형 수집 주기 선택 블록 // 1: 모듈형 수집 주기 선택 블록
item { item {
SquircleCard( SquircleCard(
containerColor = MaterialTheme.colorScheme.surface, containerColor = MaterialTheme.colorScheme.surface,
@@ -325,7 +343,7 @@ private fun NotificationTab(
} }
} }
// 키워드 등록 입력창 // 2: 키워드 등록 입력창
item { item {
SquircleCard( SquircleCard(
containerColor = MaterialTheme.colorScheme.surface, containerColor = MaterialTheme.colorScheme.surface,
@@ -408,7 +426,7 @@ private fun NotificationTab(
} }
} }
// 등록된 키워드 목록 (순서 조절 가능) // 등록된 키워드 목록 (드래그 앤 드롭 Reordering)
if (activeKeywords.isNotEmpty()) { if (activeKeywords.isNotEmpty()) {
item { item {
Row( Row(
@@ -423,11 +441,22 @@ private fun NotificationTab(
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
Spacer(modifier = Modifier.weight(1f)) Spacer(modifier = Modifier.weight(1f))
Text( Row(
text = "▲▼ 버튼으로 순서 조절", verticalAlignment = Alignment.CenterVertically,
style = MaterialTheme.typography.labelSmall, horizontalArrangement = Arrangement.spacedBy(4.dp)
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f) ) {
) Icon(
imageVector = Icons.Default.DragHandle,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),
modifier = Modifier.size(14.dp)
)
Text(
text = "길게 눌러 드래그앤드롭",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
)
}
} }
} }
@@ -436,12 +465,11 @@ private fun NotificationTab(
key = { index -> activeKeywords[index].id } key = { index -> activeKeywords[index].id }
) { index -> ) { index ->
val keyword = activeKeywords[index] val keyword = activeKeywords[index]
val itemIndex = index + 4 // 헤더 3개 + 서브헤더 1개
OneUIKeywordTile( OneUIKeywordTile(
keyword = keyword, keyword = keyword,
isFirst = index == 0, modifier = Modifier.dragDropItem(itemIndex, dragDropState),
isLast = index == activeKeywords.lastIndex,
onMoveUp = { viewModel.reorderKeywords(index, index - 1) },
onMoveDown = { viewModel.reorderKeywords(index, index + 1) },
onToggle = { viewModel.toggleKeyword(keyword.id, !keyword.isEnabled) }, onToggle = { viewModel.toggleKeyword(keyword.id, !keyword.isEnabled) },
onDelete = { viewModel.deleteKeyword(keyword.id) } onDelete = { viewModel.deleteKeyword(keyword.id) }
) )
@@ -451,17 +479,31 @@ private fun NotificationTab(
} }
// ============================================ // ============================================
// 탭 2: 사이트 관리 (SitesTab - 순서 조절 지원) // 탭 2: 사이트 관리 (SitesTab - 완벽한 드래그앤드롭)
// ============================================ // ============================================
@Composable @Composable
private fun SitesTab(viewModel: MainViewModel) { private fun SitesTab(viewModel: MainViewModel) {
val uiState by viewModel.uiState.collectAsState() val uiState by viewModel.uiState.collectAsState()
val siteOrder by viewModel.siteOrder.collectAsState() val siteOrder by viewModel.siteOrder.collectAsState()
val listState = rememberLazyListState()
val dragDropState = rememberDragDropListState(
lazyListState = listState,
onMove = { from, to ->
val fromSiteIndex = from - 1 // 상단 헤더 1개 제외
val toSiteIndex = to - 1
if (fromSiteIndex in siteOrder.indices && toSiteIndex in siteOrder.indices) {
viewModel.reorderSites(fromSiteIndex, toSiteIndex)
}
}
)
LazyColumn( LazyColumn(
state = listState,
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(horizontal = 14.dp), .padding(horizontal = 14.dp)
.dragDropGesture(dragDropState),
verticalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(top = 6.dp, bottom = 24.dp) contentPadding = PaddingValues(top = 6.dp, bottom = 24.dp)
) { ) {
@@ -473,7 +515,7 @@ private fun SitesTab(viewModel: MainViewModel) {
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Icon( Icon(
imageVector = Icons.Outlined.SwapVert, imageVector = Icons.Outlined.DragIndicator,
contentDescription = null, contentDescription = null,
tint = MaterialTheme.colorScheme.primary, tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp) modifier = Modifier.size(18.dp)
@@ -481,12 +523,12 @@ private fun SitesTab(viewModel: MainViewModel) {
Spacer(modifier = Modifier.width(6.dp)) Spacer(modifier = Modifier.width(6.dp))
Column(modifier = Modifier.weight(1f)) { Column(modifier = Modifier.weight(1f)) {
Text( Text(
text = "수집 대상 커뮤니티 및 우선순위", text = "수집 대상 커뮤니티 순서 조절",
style = MaterialTheme.typography.titleSmall, style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
Text( Text(
text = "▲▼ 버튼으로 순서를 변경하면 메인 필터에 즉시 반영됩니다.", text = "카드를 길게 눌러 위아래로 끌어놓으면 메인 필터에 즉시 반영됩니다.",
style = MaterialTheme.typography.bodySmall.copy(fontSize = 11.sp), style = MaterialTheme.typography.bodySmall.copy(fontSize = 11.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -502,13 +544,12 @@ private fun SitesTab(viewModel: MainViewModel) {
) { index -> ) { index ->
val site = siteOrder[index] val site = siteOrder[index]
val configs = successState.siteConfigs.filter { it.siteName == site.name } val configs = successState.siteConfigs.filter { it.siteName == site.name }
val itemIndex = index + 1
OneUISiteBentoCard( OneUISiteBentoCard(
siteType = site, siteType = site,
configs = configs, configs = configs,
isFirst = index == 0, modifier = Modifier.dragDropItem(itemIndex, dragDropState),
isLast = index == siteOrder.lastIndex,
onMoveUp = { viewModel.reorderSites(index, index - 1) },
onMoveDown = { viewModel.reorderSites(index, index + 1) },
onToggle = { key, enabled -> viewModel.toggleSiteConfig(key, enabled) } onToggle = { key, enabled -> viewModel.toggleSiteConfig(key, enabled) }
) )
} }
@@ -528,16 +569,22 @@ private fun SitesTab(viewModel: MainViewModel) {
} }
// ============================================ // ============================================
// 탭 3: 데이터 & 정보 (MoreTab) // 탭 3: 데이터 & 정보 (MoreTab - 자동 다운로드 & 설치 화면 호출)
// ============================================ // ============================================
@Composable @Composable
private fun MoreTab(viewModel: MainViewModel) { private fun MoreTab(viewModel: MainViewModel) {
val context = LocalContext.current val context = LocalContext.current
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
var showDeleteDialog by remember { mutableStateOf(false) } var showDeleteDialog by remember { mutableStateOf(false) }
var isCheckingUpdate by remember { mutableStateOf(false) }
val toastEvent by viewModel.toastEvent.collectAsStateWithLifecycle(initialValue = null) var isCheckingUpdate by remember { mutableStateOf(false) }
var availableUpdateInfo by remember { mutableStateOf<UpdateInfo?>(null) }
var showUpdateDialog by remember { mutableStateOf(false) }
var isDownloading by remember { mutableStateOf(false) }
var downloadProgress by remember { mutableStateOf(0) }
val toastEvent by viewModel.toastEvent.collectAsState(initial = null)
LaunchedEffect(toastEvent) { LaunchedEffect(toastEvent) {
toastEvent?.let { msg -> toastEvent?.let { msg ->
@@ -597,36 +644,55 @@ private fun MoreTab(viewModel: MainViewModel) {
Spacer(modifier = Modifier.height(14.dp)) Spacer(modifier = Modifier.height(14.dp))
Button( if (isDownloading) {
onClick = { Column(
scope.launch { horizontalAlignment = Alignment.CenterHorizontally,
isCheckingUpdate = true modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp)
val currentCode = VersionManager.getCurrentVersionCode(context) ) {
val remoteInfo = VersionManager.checkForUpdate() LinearProgressIndicator(
isCheckingUpdate = false progress = { downloadProgress / 100f },
modifier = Modifier.fillMaxWidth().height(6.dp).clip(CornerRadius.shapePill)
)
Spacer(modifier = Modifier.height(6.dp))
Text(
text = "업데이트 다운로드 중... ($downloadProgress%)",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary
)
}
} else {
Button(
onClick = {
scope.launch {
isCheckingUpdate = true
val currentCode = VersionManager.getCurrentVersionCode(context)
val remoteInfo = VersionManager.checkForUpdate()
isCheckingUpdate = false
if (remoteInfo != null && VersionManager.isUpdateAvailable(currentCode, remoteInfo.versionCode)) { if (remoteInfo != null && VersionManager.isUpdateAvailable(currentCode, remoteInfo.versionCode)) {
Toast.makeText(context, "새 버전(${remoteInfo.version})이 있습니다!", Toast.LENGTH_LONG).show() availableUpdateInfo = remoteInfo
} else { showUpdateDialog = true
Toast.makeText(context, "최신 버전을 사용 중입니다", Toast.LENGTH_SHORT).show() } else {
Toast.makeText(context, "최신 버전을 사용 중입니다 (v${VersionManager.getCurrentVersion(context)})", Toast.LENGTH_SHORT).show()
}
} }
} },
}, shape = CornerRadius.shapeNormal,
shape = CornerRadius.shapeNormal, modifier = Modifier.height(42.dp),
modifier = Modifier.height(42.dp), enabled = !isCheckingUpdate
enabled = !isCheckingUpdate ) {
) { Icon(
Icon( imageVector = Icons.Outlined.SystemUpdate,
imageVector = Icons.Outlined.SystemUpdate, contentDescription = null,
contentDescription = null, modifier = Modifier.size(16.dp)
modifier = Modifier.size(16.dp) )
) Spacer(modifier = Modifier.width(6.dp))
Spacer(modifier = Modifier.width(6.dp)) Text(
Text( text = if (isCheckingUpdate) "확인 중..." else "업데이트 확인",
text = if (isCheckingUpdate) "확인 중..." else "업데이트 확인", fontWeight = FontWeight.SemiBold,
fontWeight = FontWeight.SemiBold, fontSize = 13.sp
fontSize = 13.sp )
) }
} }
} }
} }
@@ -687,6 +753,102 @@ private fun MoreTab(viewModel: MainViewModel) {
} }
} }
// 새 버전 업데이트 발견 다이얼로그 (Changelog 및 즉시 다운로드/설치)
if (showUpdateDialog && availableUpdateInfo != null) {
val info = availableUpdateInfo!!
AlertDialog(
onDismissRequest = { if (!isDownloading) showUpdateDialog = false },
title = {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Filled.NewReleases,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Text("새 버전 업데이트 (v${info.version})")
}
},
text = {
Column {
Text(
text = "최신 버전으로 업데이트할 수 있습니다.",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold
)
if (info.changelog.isNotEmpty()) {
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "업데이트 내용:",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(4.dp))
info.changelog.forEach { log ->
Text(
text = "$log",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
},
confirmButton = {
Button(
onClick = {
showUpdateDialog = false
isDownloading = true
downloadProgress = 0
val downloadId = ApkDownloadManager.downloadApk(context, info)
// 1. 브로드캐스트 리시버로 다운로드 완료 감지
ApkDownloadManager.registerDownloadCompleteReceiver(
context = context,
downloadId = downloadId,
onComplete = {
isDownloading = false
downloadProgress = 100
// 다운로드 완료 즉시 안드로이드 시스템 설치 화면 실행!
ApkDownloadManager.installApk(context)
},
onFailed = {
isDownloading = false
Toast.makeText(context, "다운로드에 실패했습니다.", Toast.LENGTH_SHORT).show()
}
)
// 2. 프로그레스 폴링 코루틴
scope.launch {
while (isDownloading) {
delay(500)
val status = ApkDownloadManager.getDownloadStatus(context, downloadId)
downloadProgress = status.progress
if (status.isComplete) {
isDownloading = false
ApkDownloadManager.installApk(context)
break
}
if (status.isFailed) {
isDownloading = false
break
}
}
}
}
) {
Text("지금 업데이트 & 설치")
}
},
dismissButton = {
TextButton(onClick = { showUpdateDialog = false }) {
Text("나중에")
}
}
)
}
if (showDeleteDialog) { if (showDeleteDialog) {
AlertDialog( AlertDialog(
onDismissRequest = { showDeleteDialog = false }, onDismissRequest = { showDeleteDialog = false },
@@ -713,7 +875,7 @@ private fun MoreTab(viewModel: MainViewModel) {
} }
// ============================================ // ============================================
// 서브 컴포넌트들 (순서 조절 버튼 포함) // 서브 컴포넌트들 (드래그 핸들러 포함)
// ============================================ // ============================================
@Composable @Composable
@@ -762,56 +924,29 @@ private fun BentoMiniTile(
@Composable @Composable
private fun OneUIKeywordTile( private fun OneUIKeywordTile(
keyword: Keyword, keyword: Keyword,
isFirst: Boolean, modifier: Modifier = Modifier,
isLast: Boolean,
onMoveUp: () -> Unit,
onMoveDown: () -> Unit,
onToggle: () -> Unit, onToggle: () -> Unit,
onDelete: () -> Unit onDelete: () -> Unit
) { ) {
SquircleCard( SquircleCard(
shape = CornerRadius.shapeNormal, shape = CornerRadius.shapeNormal,
containerColor = MaterialTheme.colorScheme.surface, containerColor = MaterialTheme.colorScheme.surface,
modifier = Modifier.fillMaxWidth() modifier = modifier.fillMaxWidth()
) { ) {
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp), .padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
// 순서 조절 상/하 버튼 Icon(
Column( imageVector = Icons.Default.DragHandle,
horizontalAlignment = Alignment.CenterHorizontally, contentDescription = "드래그하여 순서 변경",
verticalArrangement = Arrangement.Center tint = MaterialTheme.colorScheme.outline.copy(alpha = 0.55f),
) { modifier = Modifier.size(20.dp)
IconButton( )
onClick = onMoveUp,
enabled = !isFirst,
modifier = Modifier.size(22.dp)
) {
Icon(
imageVector = Icons.Filled.KeyboardArrowUp,
contentDescription = "위로 이동",
tint = if (!isFirst) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
modifier = Modifier.size(16.dp)
)
}
IconButton(
onClick = onMoveDown,
enabled = !isLast,
modifier = Modifier.size(22.dp)
) {
Icon(
imageVector = Icons.Filled.KeyboardArrowDown,
contentDescription = "아래로 이동",
tint = if (!isLast) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
modifier = Modifier.size(16.dp)
)
}
}
Spacer(modifier = Modifier.width(6.dp)) Spacer(modifier = Modifier.width(8.dp))
Box( Box(
modifier = Modifier modifier = Modifier
@@ -854,10 +989,7 @@ private fun OneUIKeywordTile(
private fun OneUISiteBentoCard( private fun OneUISiteBentoCard(
siteType: SiteType, siteType: SiteType,
configs: List<SiteConfig>, configs: List<SiteConfig>,
isFirst: Boolean, modifier: Modifier = Modifier,
isLast: Boolean,
onMoveUp: () -> Unit,
onMoveDown: () -> Unit,
onToggle: (String, Boolean) -> Unit onToggle: (String, Boolean) -> Unit
) { ) {
val siteColor = getSiteColor(siteType) val siteColor = getSiteColor(siteType)
@@ -869,7 +1001,7 @@ private fun OneUISiteBentoCard(
containerColor = MaterialTheme.colorScheme.surface, containerColor = MaterialTheme.colorScheme.surface,
borderColor = if (isAnyEnabled) siteColor.copy(alpha = 0.4f) else MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f), borderColor = if (isAnyEnabled) siteColor.copy(alpha = 0.4f) else MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f),
borderWidth = if (isAnyEnabled) 1.2.dp else 0.8.dp, borderWidth = if (isAnyEnabled) 1.2.dp else 0.8.dp,
modifier = Modifier.fillMaxWidth() modifier = modifier.fillMaxWidth()
) { ) {
Column(modifier = Modifier.padding(12.dp)) { Column(modifier = Modifier.padding(12.dp)) {
// 상단 마스터 행 // 상단 마스터 행
@@ -877,38 +1009,14 @@ private fun OneUISiteBentoCard(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
// 순서 조절 버튼 Icon(
Column( imageVector = Icons.Default.DragHandle,
horizontalAlignment = Alignment.CenterHorizontally, contentDescription = "드래그하여 순서 변경",
verticalArrangement = Arrangement.Center tint = MaterialTheme.colorScheme.outline.copy(alpha = 0.55f),
) { modifier = Modifier.size(20.dp)
IconButton( )
onClick = onMoveUp,
enabled = !isFirst,
modifier = Modifier.size(22.dp)
) {
Icon(
imageVector = Icons.Filled.KeyboardArrowUp,
contentDescription = "위로 이동",
tint = if (!isFirst) siteColor else MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
modifier = Modifier.size(16.dp)
)
}
IconButton(
onClick = onMoveDown,
enabled = !isLast,
modifier = Modifier.size(22.dp)
) {
Icon(
imageVector = Icons.Filled.KeyboardArrowDown,
contentDescription = "아래로 이동",
tint = if (!isLast) siteColor else MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
modifier = Modifier.size(16.dp)
)
}
}
Spacer(modifier = Modifier.width(6.dp)) Spacer(modifier = Modifier.width(8.dp))
// 브랜드 뱃지 // 브랜드 뱃지
Surface( Surface(
@@ -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,
+6 -6
View File
@@ -1,10 +1,10 @@
{ {
"version": "0.2.8", "version": "0.2.9",
"versionCode": 28, "versionCode": 29,
"updateUrl": "https://git.webpluss.net/sanjeok77/hotdeal_alarm/releases/download/v0.2.8/app-release.apk", "updateUrl": "https://git.webpluss.net/sanjeok77/hotdeal_alarm/releases/download/v0.2.9/app-release.apk",
"changelog": [ "changelog": [
"설정 > 사이트 관리에서 사이트 순서 조절 기능 추가 (메인 필터 칩 순서 실시간 연동)", "사이트 및 키워드 순서 조절을 터치 드래그 앤 드롭(Drag & Drop) 방식으로 전면 업그레이드",
"설정 > 등록된 키워드 목록에서 키워드 순서 조절 기능 추가", "앱 내 업데이트 시 다운로드 완료 후 설치 화면으로 안 넘어가는 버그 수정",
"하단 고정 메뉴 높이 및 마진 슬림화로 메인 화면 영역 추가 확보" "새 버전 업데이트 안내 다이얼로그 및 진행률 프로그레스 바 연동"
] ]
} }