Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 380b2c5a6c | |||
| fdcbb615ab | |||
| 161cc8060d | |||
| 6c2dec6cd3 | |||
| fa4c50a054 | |||
| 707d81d850 | |||
| 4d8861d79c | |||
| b60aa517b9 | |||
| 357788adb9 | |||
| a17eee8884 | |||
| f4f5599117 |
@@ -1,143 +0,0 @@
|
||||
# Git 푸시 성공 가이드
|
||||
|
||||
## 빠른 실행
|
||||
|
||||
```bash
|
||||
# 1. gh CLI 인증 확인
|
||||
./gh.exe auth status
|
||||
|
||||
# 2. 인증이 안 되어 있으면 로그인
|
||||
./gh.exe auth login --web
|
||||
|
||||
# 3. Git에 gh 인증 설정
|
||||
./gh.exe auth setup-git
|
||||
|
||||
# 4. 푸시
|
||||
git push shiftring main
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 상세 절차
|
||||
|
||||
### 1. GitHub CLI 인증
|
||||
|
||||
```bash
|
||||
# 인증 상태 확인
|
||||
./gh.exe auth status
|
||||
```
|
||||
|
||||
**인증이 안 된 경우:**
|
||||
```bash
|
||||
./gh.exe auth login --web
|
||||
```
|
||||
- One-time code가 표시됨 (예: C7EF-30B3)
|
||||
- https://github.com/login/device 접속
|
||||
- 코드 입력 후 인증 완료
|
||||
|
||||
### 2. Git에 gh 인증 연동
|
||||
|
||||
```bash
|
||||
./gh.exe auth setup-git
|
||||
```
|
||||
|
||||
### 3. 푸시 실행
|
||||
|
||||
```bash
|
||||
# shiftring remote 사용 (agent.md에 정의됨)
|
||||
git push shiftring main
|
||||
|
||||
# 또는 origin 사용
|
||||
git push origin main
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 저장소 정보
|
||||
|
||||
| Remote | URL | 용도 |
|
||||
|--------|-----|------|
|
||||
| origin | https://github.com/sanjeok77-tech/ShiftRing.git | 코드 저장소 |
|
||||
| shiftring | https://github.com/sanjeok77-tech/ShiftRing.git | 코드 저장소 (동일) |
|
||||
|
||||
---
|
||||
|
||||
## 문제 해결
|
||||
|
||||
### "Cannot prompt because user interactivity has been disabled"
|
||||
|
||||
**원인**: 환경 변수로 인해 인터랙티브 프롬프트가 비활성화됨
|
||||
|
||||
**해결**:
|
||||
```bash
|
||||
# gh CLI로 인증 설정
|
||||
./gh.exe auth setup-git
|
||||
|
||||
# 그 다음 푸시
|
||||
git push shiftring main
|
||||
```
|
||||
|
||||
### "Host key verification failed" (SSH)
|
||||
|
||||
**원인**: SSH 키가 설정되지 않음
|
||||
|
||||
**해결**: HTTPS 사용
|
||||
```bash
|
||||
git remote set-url origin https://github.com/sanjeok77-tech/ShiftRing.git
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 릴리즈 푸시 (dakjaba-releases)
|
||||
|
||||
```bash
|
||||
# 1. 버전 파일 업데이트
|
||||
# version.json, CHANGELOG.md, README.md 수정
|
||||
|
||||
# 2. APK 복사
|
||||
cp app/build/outputs/apk/release/app-release.apk app.apk
|
||||
|
||||
# 3. GitHub Release 생성
|
||||
./gh.exe release create v1.1.4 "app.apk" \
|
||||
--title "Shiftring v1.1.4" \
|
||||
--notes "릴리즈 노트" \
|
||||
-R "sanjeok77-tech/dakjaba-releases"
|
||||
|
||||
# 4. dakjaba-releases 저장소 업데이트
|
||||
./gh.exe repo clone sanjeok77-tech/dakjaba-releases ../dakjaba-releases-temp
|
||||
cp version.json ../dakjaba-releases-temp/
|
||||
cp app.apk ../dakjaba-releases-temp/
|
||||
cd ../dakjaba-releases-temp
|
||||
git add . && git commit -m "update: vX.X.X" && git push origin main
|
||||
cd ..
|
||||
rm -rf dakjaba-releases-temp
|
||||
|
||||
# 5. 소스 코드 커밋 및 푸시
|
||||
cd /c/Users/work/Desktop/1.0.0
|
||||
git add . && git commit -m "chore: release vX.X.X"
|
||||
git push shiftring main
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 성공 사례 (2026-02-21)
|
||||
|
||||
```bash
|
||||
$ ./gh.exe auth status
|
||||
github.com
|
||||
✓ Logged in to github.com account sanjeok77-tech (keyring)
|
||||
- Active account: true
|
||||
- Git operations protocol: https
|
||||
- Token: gho_************************************
|
||||
|
||||
$ ./gh.exe auth setup-git
|
||||
git: authorization completed
|
||||
|
||||
$ git push shiftring main
|
||||
To https://github.com/sanjeok77-tech/ShiftRing.git
|
||||
a848cd8..c72db7f main -> main
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**최종 수정**: 2026-02-21
|
||||
@@ -1,70 +0,0 @@
|
||||
---
|
||||
description: 릴리즈 빌드 및 배포 자동화 가이드 (GitHub CLI 기반)
|
||||
---
|
||||
|
||||
# 🚀 릴리즈 빌드 및 배포 워크플로우
|
||||
|
||||
이 가이드는 교대링(Shiftring) 프로젝트의 최신 버전을 빌드하고, APK를 배포 저장소(`dakjaba-releases`)에 업로드하며, 버전을 갱신하는 절차를 설명합니다.
|
||||
|
||||
## // turbo-all
|
||||
## 1. 전제 조건
|
||||
- **GitHub CLI (gh)**가 설치되어 있고 로그인되어 있어야 함 (`gh auth status`)
|
||||
- `release.jks`와 `keystore.properties`가 루트 폴더에 존재해야 함
|
||||
|
||||
## 2. 배포 단계
|
||||
|
||||
### 단계 1: 프로젝트 버전 확인 및 갱신
|
||||
- `app/build.gradle.kts`의 `versionCode`와 `versionName`을 확인 및 갱신합니다.
|
||||
- `version.json`의 정보를 동일하게 맞춥니다.
|
||||
- `CHANGELOG.md`에 변경 사항을 기록합니다.
|
||||
- `README.md`의 다운로드 링크 및 버전을 갱신합니다.
|
||||
|
||||
### 단계 2: 릴리즈 빌드 수행
|
||||
```powershell
|
||||
./gradlew.bat assembleRelease
|
||||
```
|
||||
- 빌드 결과물은 `app/build/outputs/apk/release/app-release.apk`에 생성됩니다.
|
||||
|
||||
### 단계 3: APK 서명 확인 (선택 사항)
|
||||
- 생성된 APK가 정상적으로 서명되었는지 확인합니다.
|
||||
|
||||
### 단계 4: 배포 저장소 업데이트 및 릴리즈 생성
|
||||
// turbo
|
||||
```powershell
|
||||
# 1. APK 파일 복사 (배포용 이름으로 변경)
|
||||
copy-item "app/build/outputs/apk/release/app-release.apk" "app.apk" -Force
|
||||
|
||||
# 2. 버전 정보 설정 (현재 버전에 맞춰 수정)
|
||||
$VERSION = "v1.0.4"
|
||||
|
||||
# 3. GitHub Release 생성 (dakjaba-releases 저장소)
|
||||
# tip: 이미 존재하는 태그라면 삭제 후 생성하거나 gh release edit 사용
|
||||
gh release create $VERSION "app.apk" --title "Shiftring $VERSION" --notes-file "CHANGELOG.md" -R "sanjeok77-tech/dakjaba-releases"
|
||||
|
||||
# 4. 배포 저장소(dakjaba-releases)의 version.json 및 최신 APK 갱신 (인앱 업데이트용)
|
||||
gh repo clone sanjeok77-tech/dakjaba-releases ..\dakjaba-releases-temp
|
||||
copy-item "version.json" "..\dakjaba-releases-temp\version.json" -Force
|
||||
copy-item "app.apk" "..\dakjaba-releases-temp\app.apk" -Force
|
||||
|
||||
# 5. README.md 자동 업데이트 (v1.1.1 패턴 기반 교체 예시 - 실제 버전변수로 대체 필요)
|
||||
# tip: sed나 powershell replace를 사용하여 README의 vX.X.X 및 다운로드 링크를 갱신합니다.
|
||||
(Get-Content README.md) -replace 'v\d+\.\d+\.\d+', "$VERSION" | Set-Content README.md
|
||||
(Get-Content ..\dakjaba-releases-temp\README.md) -replace 'v\d+\.\d+\.\d+', "$VERSION" | Set-Content ..\dakjaba-releases-temp\README.md
|
||||
|
||||
pushd ..\dakjaba-releases-temp
|
||||
git add .
|
||||
git commit -m "update: $VERSION"
|
||||
git push origin main
|
||||
popd
|
||||
Remove-Item -Recurse -Force ..\dakjaba-releases-temp
|
||||
```
|
||||
|
||||
### 단계 5: 소스 코드 커밋 및 푸시
|
||||
```powershell
|
||||
git add .
|
||||
git commit -m "chore: release $VERSION"
|
||||
git push origin main
|
||||
```
|
||||
|
||||
---
|
||||
*주의: 배포 저장소(`dakjaba-releases`)는 퍼블릭이며, 코드 저장소(`dakjaba`)는 프라이빗입니다. 배포 시 중요한 키 파일이 배포 저장소에 포함되지 않도록 주의하십시오.*
|
||||
@@ -1,7 +1,9 @@
|
||||
# Shift Alarm (교대링 - 전주/논산)
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/Download-Release_v1.1.9-blue?style=for-the-badge&logo=android&logoColor=white">
|
||||
<a href="https://git.webpluss.net/sanjeok77/ShiftRing/releases/tag/v1.1.9">
|
||||
<img src="https://img.shields.io/badge/Download-Release_v1.1.9-blue?style=for-the-badge&logo=android&logoColor=white">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
[** 최신 버전 (v1.1.9) 다운로드 (APK)**](https://git.webpluss.net/sanjeok77/ShiftRing/releases/download/v1.1.9/app.apk)
|
||||
|
||||
55
RELEASE_UPLOAD_GUIDE.md
Normal file
55
RELEASE_UPLOAD_GUIDE.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# Gitea Release에 APK 업로드 방법
|
||||
|
||||
## 환경
|
||||
- Git 호스팅: git.webpluss.net (Gitea)
|
||||
- 저장소: sanjeok77/ShiftRing
|
||||
- 태그: v1.1.9
|
||||
- APK 경로: C:\Users\work\Desktop\1.0.0\app.apk
|
||||
|
||||
## 1. Release ID 확인
|
||||
|
||||
```bash
|
||||
# Release 목록 조회
|
||||
curl -s "https://git.webpluss.net/api/v1/repos/sanjeok77/ShiftRing/releases"
|
||||
```
|
||||
|
||||
응답에서 Release ID 확인 (예: `id: 5`)
|
||||
|
||||
## 2. APK 업로드
|
||||
|
||||
```bash
|
||||
# Personal Access Token 사용
|
||||
curl -s -u "username:TOKEN" \
|
||||
-X POST "https://git.webpluss.net/api/v1/repos/sanjeok77/ShiftRing/releases/5/assets" \
|
||||
-F "attachment=@C:/Users/work/Desktop/1.0.0/app.apk" \
|
||||
-F "name=app.apk"
|
||||
```
|
||||
|
||||
## 3. 릴리즈 설명 수정 (한글 깨짐 방지)
|
||||
|
||||
```bash
|
||||
# --data-binary 사용하고 stdin으로 JSON 전달
|
||||
curl -s -u "sanjeok77:TOKEN" \
|
||||
-X PATCH "https://git.webpluss.net/api/v1/repos/sanjeok77/ShiftRing/releases/5" \
|
||||
-H "Content-Type: application/json; charset=utf-8" \
|
||||
--data-binary @- << 'EOF'
|
||||
{"body":"## v1.1.9 - 수정 내용\n\n- 수정사항 1\n- 수정사항 2\n\nNo description provided"}
|
||||
EOF
|
||||
```
|
||||
|
||||
### 한글 깨짐 방지 팁
|
||||
- `-H "Content-Type: application/json; charset=utf-8"` 추가
|
||||
- `--data-binary @-` 사용 (stdin에서 읽기)
|
||||
- `<< 'EOF'` 로 HEREDOC 사용 (변수展開 방지)
|
||||
|
||||
## 4. 확인
|
||||
|
||||
```bash
|
||||
# 릴리즈 정보 조회
|
||||
curl -s "https://git.webpluss.net/api/v1/repos/sanjeok77/ShiftRing/releases/5"
|
||||
```
|
||||
|
||||
## 참고
|
||||
- GitLab이 아닌 **Gitea** 이므로 API 경로가 다름
|
||||
- GitLab: `/api/v4/projects/:id/releases`
|
||||
- Gitea: `/api/v1/repos/:owner/:repo/releases/:id`
|
||||
31
agent.md
31
agent.md
@@ -46,42 +46,31 @@
|
||||
```
|
||||
|
||||
### 3.3 릴리즈 순서
|
||||
|
||||
> **참고**: Gitea Release APK 업로드 방법은 [RELEASE_UPLOAD_GUIDE.md](./RELEASE_UPLOAD_GUIDE.md) 문서를 참조하세요.
|
||||
|
||||
1. **버전 업데이트**: `build.gradle.kts`에서 `versionCode`와 `versionName`을 올린다.
|
||||
- 예: `versionCode = 101`, `versionName = "1.0.1"`
|
||||
- 예: `versionCode = 1120`, `versionName = "1.2.0"`
|
||||
2. **빌드**: 릴리즈 빌드 수행
|
||||
```bash
|
||||
./gradlew assembleRelease
|
||||
```
|
||||
3. **릴리즈 생성**: GitLab 웹 인터페이스 또는 CLI 사용
|
||||
```bash
|
||||
# 1) ShiftRing 리포지토리에 푸시
|
||||
git push shiftring main
|
||||
|
||||
# 2) 기존 릴리즈 삭제 (필요시)
|
||||
gh release delete v1.0.1 --repo sanjeok77/ShiftRing -y
|
||||
|
||||
# 3) 신규 릴리즈 생성
|
||||
gh release create v1.0.1 \
|
||||
--repo sanjeok77/ShiftRing \
|
||||
--title "v1.0.1 - 릴리즈 제목" \
|
||||
--notes "릴리즈 노트 내용" \
|
||||
app/build/outputs/apk/release/app-release.apk
|
||||
```
|
||||
3. **릴리즈 생성**: Gitea API 또는 웹 인터페이스 사용
|
||||
- 자세한 방법은 [RELEASE_UPLOAD_GUIDE.md](./RELEASE_UPLOAD_GUIDE.md) 참조
|
||||
4. **version.json 업데이트**: ShiftRing 리포지토리 루트에 `version.json` 파일 생성/수정
|
||||
```json
|
||||
{
|
||||
"versionCode": 101,
|
||||
"versionName": "1.0.1",
|
||||
"apkUrl": "https://git.webpluss.net/sanjeok77/ShiftRing/releases/download/v1.0.0/app.apk",
|
||||
"versionCode": 1120,
|
||||
"versionName": "1.2.0",
|
||||
"apkUrl": "https://git.webpluss.net/sanjeok77/ShiftRing/releases/download/v1.2.0/app.apk",
|
||||
"changelog": "수정사항 요약"
|
||||
}
|
||||
```
|
||||
5. **소스 코드 커밋**: 코드 저장소에 변경 사항 푸시
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "Release v1.0.1"
|
||||
git commit -m "Release v1.2.0"
|
||||
git push origin main
|
||||
git push shiftring main
|
||||
```
|
||||
|
||||
### 3.4 저장소 정보 (단일 저장소 전략)
|
||||
|
||||
@@ -20,8 +20,8 @@ android {
|
||||
applicationId = "com.example.shiftalarm"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 1119
|
||||
versionName = "1.1.9"
|
||||
versionCode = 1124
|
||||
versionName = "1.2.4"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
@@ -78,6 +78,14 @@ class AlarmActivity : AppCompatActivity() {
|
||||
|
||||
// 알람 시작 (화면 상태와 무관하게 항상 실행)
|
||||
startAlarm()
|
||||
|
||||
// 마스터 알람이 꺼져있으면 알람 화면을 즉시 종료
|
||||
val prefs = getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
if (!ShiftAlarmDefaults.isMasterAlarmEnabled(prefs)) {
|
||||
Toast.makeText(this, "전체 알람이 꺼져있습니다.", Toast.LENGTH_SHORT).show()
|
||||
finish()
|
||||
return
|
||||
}
|
||||
setupControls()
|
||||
|
||||
// 5분 후 자동 스누즈
|
||||
@@ -209,6 +217,7 @@ class AlarmActivity : AppCompatActivity() {
|
||||
val dx = event.rawX - startX
|
||||
if (abs(dx) > maxSwipe * 0.8f) {
|
||||
// Trigger Dismiss
|
||||
@Suppress("DEPRECATION")
|
||||
(getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator)?.vibrate(50)
|
||||
Toast.makeText(this, "알람 해제 완료", Toast.LENGTH_SHORT).show()
|
||||
stopAlarm(); finish()
|
||||
@@ -247,6 +256,7 @@ class AlarmActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
private fun handleSnooze() {
|
||||
@Suppress("DEPRECATION")
|
||||
(getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator)?.vibrate(50)
|
||||
val snoozeRepeat = intent.getIntExtra("EXTRA_SNOOZE_REPEAT", 3)
|
||||
val text = if (snoozeRepeat == 99) "다시 울림 설정됨" else "다시 울림 (${snoozeRepeat}회 남음)"
|
||||
@@ -274,21 +284,25 @@ class AlarmActivity : AppCompatActivity() {
|
||||
else android.provider.Settings.System.DEFAULT_ALARM_ALERT_URI
|
||||
}
|
||||
|
||||
// AudioAttributes 강화: 화면 켜진 상태에서도 알람음이 울리도록
|
||||
// AudioAttributes 강화: 무음/진동 모드에서도 알람음이 울리도록
|
||||
val audioAttrs = AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_ALARM)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||
.setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED) // 볼륨 강제 적용
|
||||
.setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
|
||||
.build()
|
||||
|
||||
// AudioManager를 통해 알람 볼륨 설정
|
||||
// AudioManager를 통해 알람 볼륨 설정 및 무음 모드 우회
|
||||
val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val originalVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM)
|
||||
val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM)
|
||||
|
||||
// 무음 모드에서도 알람음이 울리도록 STREAM_ALARM 사용 (벨소리와 독립)
|
||||
// 알람 스트림은 다른 스트림과 달리 무음 모드에서도 울림
|
||||
val originalRingerMode = audioManager.ringerMode
|
||||
|
||||
// 알람 볼륨을 최대로 설정 (사용자가 나중에 조정 가능)
|
||||
try {
|
||||
val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM)
|
||||
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume, 0)
|
||||
Log.d("AlarmActivity", "알람 볼륨 설정: $maxVolume (RingerMode: $originalRingerMode)")
|
||||
} catch (e: Exception) {
|
||||
Log.w("AlarmActivity", "알람 볼륨 설정 실패", e)
|
||||
}
|
||||
|
||||
@@ -13,56 +13,102 @@ class AlarmReceiver : BroadcastReceiver() {
|
||||
private val TAG = "AlarmReceiver"
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent?) {
|
||||
Log.d(TAG, "===== 알람 수신 (Receiver) =====")
|
||||
Log.d(TAG, "===== 알람 수신 =====")
|
||||
|
||||
val alarmId = intent?.getIntExtra("EXTRA_ALARM_ID", -1) ?: -1
|
||||
val isCustom = intent?.getBooleanExtra("EXTRA_IS_CUSTOM", false) ?: false
|
||||
|
||||
// 커스텀 알람인 경우 DB에서 여전히 유효한지 확인 (삭제된 알람이 울리는 문제 해결)
|
||||
if (isCustom && alarmId != -1) {
|
||||
val customAlarmId = intent.getIntExtra("EXTRA_UNIQUE_ID", -1)
|
||||
if (customAlarmId != -1) {
|
||||
// 비동기로 DB 확인
|
||||
val scope = CoroutineScope(Dispatchers.IO)
|
||||
scope.launch {
|
||||
val repo = ShiftRepository(context)
|
||||
val alarms = repo.getAllCustomAlarms()
|
||||
val alarmExists = alarms.any { it.id == customAlarmId && it.isEnabled }
|
||||
|
||||
if (!alarmExists) {
|
||||
Log.w(TAG, "삭제된 또는 비활성화된 알람입니다. 무시합니다. (ID: $customAlarmId)")
|
||||
scope.cancel()
|
||||
return@launch
|
||||
}
|
||||
|
||||
// 알람이 유효하면 직접 AlarmActivity 실행 + Foreground Service 시작
|
||||
startAlarm(context, intent)
|
||||
scope.cancel()
|
||||
}
|
||||
return
|
||||
}
|
||||
// 마스터 알람이 꺼져있으면 알람 무시
|
||||
val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
if (!ShiftAlarmDefaults.isMasterAlarmEnabled(prefs)) {
|
||||
Log.w(TAG, "마스터 알람이 꺼져있어 알람을 무시합니다.")
|
||||
return
|
||||
}
|
||||
|
||||
// 일반 알람은 바로 직접 실행
|
||||
startAlarm(context, intent)
|
||||
val action = intent?.action
|
||||
|
||||
when (action) {
|
||||
"com.example.shiftalarm.SNOOZE" -> {
|
||||
// 스누즈 알람
|
||||
startAlarm(context, intent)
|
||||
}
|
||||
else -> {
|
||||
// 일반 알람 - DB에서 여전히 유효한지 확인
|
||||
val alarmDbId = intent?.getIntExtra("EXTRA_ALARM_DB_ID", -1) ?: -1
|
||||
|
||||
if (alarmDbId != -1) {
|
||||
// 비동기로 DB 확인
|
||||
val scope = CoroutineScope(Dispatchers.IO)
|
||||
scope.launch {
|
||||
try {
|
||||
val repo = ShiftRepository(context)
|
||||
val alarms = repo.getAllCustomAlarms()
|
||||
val alarm = alarms.find { it.id == alarmDbId }
|
||||
|
||||
// 알람이 존재하지 않거나 비활성화되었으면 무시
|
||||
if (alarm == null) {
|
||||
Log.w(TAG, "DB에서 알람을 찾을 수 없음 (삭제됨): ID=$alarmDbId")
|
||||
scope.cancel()
|
||||
return@launch
|
||||
}
|
||||
|
||||
if (!alarm.isEnabled) {
|
||||
Log.w(TAG, "알람이 비활성화됨: ID=$alarmDbId")
|
||||
scope.cancel()
|
||||
return@launch
|
||||
}
|
||||
|
||||
// 근무 조건 확인
|
||||
val dateStr = intent?.getStringExtra("EXTRA_DATE")
|
||||
if (dateStr != null) {
|
||||
val date = java.time.LocalDate.parse(dateStr)
|
||||
val team = prefs.getString("selected_team", "A") ?: "A"
|
||||
val factory = prefs.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
val shift = repo.getShift(date, team, factory)
|
||||
|
||||
if (alarm.shiftType != "기타" && alarm.shiftType != shift) {
|
||||
Log.w(TAG, "근무 조건이 맞지 않음: 알람=${alarm.shiftType}, 실제=$shift")
|
||||
scope.cancel()
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
|
||||
// 모든 검증 통과 - 알람 실행
|
||||
startAlarm(context, intent)
|
||||
scope.cancel()
|
||||
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "알람 검증 중 오류", e)
|
||||
scope.cancel()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// DB ID가 없는 경우 (테스트 알람 등) - 바로 실행
|
||||
startAlarm(context, intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun startAlarm(context: Context, intent: Intent?) {
|
||||
// WakeLock 획득 (화면 켜기 및 Activity 실행 보장)
|
||||
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
@Suppress("DEPRECATION")
|
||||
val wakeLock = pm.newWakeLock(
|
||||
PowerManager.PARTIAL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP,
|
||||
"ShiftAlarm::AlarmWakeLock"
|
||||
)
|
||||
wakeLock.acquire(30 * 1000L) // 30초 - Activity 실행 및 초기화에 충분한 시간
|
||||
wakeLock.acquire(30 * 1000L) // 30초
|
||||
|
||||
try {
|
||||
// 1. Foreground Service 시작 (알림 표시 및 시스템에 알람 실행 중 알림)
|
||||
val shiftType = intent?.getStringExtra("EXTRA_SHIFT_TYPE") ?: "근무"
|
||||
val soundUri = intent?.getStringExtra("EXTRA_SOUND")
|
||||
val snoozeMin = intent?.getIntExtra("EXTRA_SNOOZE", 5) ?: 5
|
||||
val snoozeRepeat = intent?.getIntExtra("EXTRA_SNOOZE_REPEAT", 3) ?: 3
|
||||
|
||||
// 1. Foreground Service 시작
|
||||
val serviceIntent = Intent(context, AlarmForegroundService::class.java).apply {
|
||||
putExtra("EXTRA_SHIFT", intent?.getStringExtra("EXTRA_SHIFT") ?: "근무")
|
||||
putExtra("EXTRA_SOUND", intent?.getStringExtra("EXTRA_SOUND"))
|
||||
putExtra("EXTRA_SNOOZE", intent?.getIntExtra("EXTRA_SNOOZE", 5) ?: 5)
|
||||
putExtra("EXTRA_SNOOZE_REPEAT", intent?.getIntExtra("EXTRA_SNOOZE_REPEAT", 3) ?: 3)
|
||||
putExtra("EXTRA_SHIFT", shiftType)
|
||||
putExtra("EXTRA_SOUND", soundUri)
|
||||
putExtra("EXTRA_SNOOZE", snoozeMin)
|
||||
putExtra("EXTRA_SNOOZE_REPEAT", snoozeRepeat)
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
@@ -71,30 +117,35 @@ class AlarmReceiver : BroadcastReceiver() {
|
||||
context.startService(serviceIntent)
|
||||
}
|
||||
|
||||
// 2. AlarmActivity 직접 실행 (알람 화면 표시)
|
||||
Log.d(TAG, "ForegroundService 시작 완료")
|
||||
|
||||
// 2. AlarmActivity 직접 실행
|
||||
val activityIntent = Intent(context, AlarmActivity::class.java).apply {
|
||||
putExtra("EXTRA_SHIFT", intent?.getStringExtra("EXTRA_SHIFT") ?: "근무")
|
||||
putExtra("EXTRA_SOUND", intent?.getStringExtra("EXTRA_SOUND"))
|
||||
putExtra("EXTRA_SNOOZE", intent?.getIntExtra("EXTRA_SNOOZE", 5) ?: 5)
|
||||
putExtra("EXTRA_SNOOZE_REPEAT", intent?.getIntExtra("EXTRA_SNOOZE_REPEAT", 3) ?: 3)
|
||||
// 중요: 새 태스크로 실행 (FLAG_ACTIVITY_NEW_TASK)
|
||||
putExtra("EXTRA_SHIFT", shiftType)
|
||||
putExtra("EXTRA_SOUND", soundUri)
|
||||
putExtra("EXTRA_SNOOZE", snoozeMin)
|
||||
putExtra("EXTRA_SNOOZE_REPEAT", snoozeRepeat)
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
// 기존 인스턴스 재사용 및 최상위로 가져오기
|
||||
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
// 잠금 화면 위에 표시
|
||||
addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
|
||||
// 화면 켜기
|
||||
addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
|
||||
}
|
||||
|
||||
context.startActivity(activityIntent)
|
||||
Log.d(TAG, "AlarmActivity 실행 완료")
|
||||
// 지연 후 Activity 시작 (ForegroundService가 먼저 시작되도록)
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
|
||||
try {
|
||||
context.startActivity(activityIntent)
|
||||
Log.d(TAG, "AlarmActivity 실행 완료: $shiftType")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "AlarmActivity 실행 실패", e)
|
||||
}
|
||||
}, 500)
|
||||
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "알람 실행 실패", e)
|
||||
} finally {
|
||||
// WakeLock은 Activity가 화면을 켜고 나서 해제
|
||||
// WakeLock 해제
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
|
||||
if (wakeLock.isHeld) wakeLock.release()
|
||||
}, 5000)
|
||||
|
||||
@@ -4,25 +4,22 @@ import android.content.Context
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.time.LocalDate
|
||||
|
||||
/**
|
||||
* 알람 동기화 관리자
|
||||
* DB와 AlarmManager 간의 실시간 동기화를 보장합니다.
|
||||
* 단순화된 알람 동기화 관리자
|
||||
*
|
||||
* 동기화 전략:
|
||||
* 1. DB 작업과 AlarmManager 작업을 원자적으로 처리
|
||||
* 2. 실패 시 롤백 메커니즘 제공
|
||||
* 3. 동기화 상태 추적 및 재시도
|
||||
* 핵심 원칙:
|
||||
* 1. 알람 추가/삭제/수정 시 즉시 AlarmManager에 반영
|
||||
* 2. 복잡한 예약 취소 로직 제거 - 단순한 ID 체계 사용
|
||||
* 3. 매일 자정 WorkManager가 다음날 알람 스케줄링
|
||||
*/
|
||||
object AlarmSyncManager {
|
||||
|
||||
private const val TAG = "AlarmSyncManager"
|
||||
private const val PREFS_NAME = "AlarmSyncPrefs"
|
||||
|
||||
/**
|
||||
* 알람 추가 동기화
|
||||
* DB에 추가 후 AlarmManager에 즉시 예약
|
||||
* 알람 추가
|
||||
* DB에 추가 후 즉시 AlarmManager에 예약
|
||||
*/
|
||||
suspend fun addAlarm(context: Context, alarm: CustomAlarm): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
@@ -32,64 +29,32 @@ object AlarmSyncManager {
|
||||
val alarmId = repo.addCustomAlarm(alarm)
|
||||
Log.d(TAG, "알람 DB 추가 완료: ID=$alarmId")
|
||||
|
||||
// 2. AlarmManager에 예약
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
val customAlarms = repo.getAllCustomAlarms()
|
||||
val addedAlarm = customAlarms.find { it.id == alarmId.toInt() }
|
||||
// 2. AlarmManager에 즉시 예약
|
||||
val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
val team = prefs.getString("selected_team", "A") ?: "A"
|
||||
val factory = prefs.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
|
||||
if (addedAlarm == null) {
|
||||
Log.w(TAG, "추가된 알람을 DB에서 찾을 수 없음: ID=$alarmId")
|
||||
return@withContext Result.failure(Exception("알람을 찾을 수 없습니다"))
|
||||
}
|
||||
|
||||
if (addedAlarm.isEnabled) {
|
||||
// 향후 30일치 예약
|
||||
for (i in 0 until 30) {
|
||||
val targetDate = today.plusDays(i.toLong())
|
||||
val shift = repo.getShift(targetDate,
|
||||
context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
.getString("selected_team", "A") ?: "A",
|
||||
context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
)
|
||||
|
||||
if (addedAlarm.shiftType == "기타" || addedAlarm.shiftType == shift) {
|
||||
scheduleCustomAlarm(
|
||||
context,
|
||||
targetDate,
|
||||
addedAlarm.id,
|
||||
addedAlarm.shiftType,
|
||||
addedAlarm.time,
|
||||
addedAlarm.soundUri,
|
||||
addedAlarm.snoozeInterval,
|
||||
addedAlarm.snoozeRepeat
|
||||
)
|
||||
}
|
||||
}
|
||||
Log.d(TAG, "알람 AlarmManager 예약 완료: ID=$alarmId")
|
||||
}
|
||||
|
||||
// 3. 동기화 상태 저장
|
||||
saveSyncStatus(context, "last_add_alarm", System.currentTimeMillis())
|
||||
val addedAlarm = alarm.copy(id = alarmId.toInt())
|
||||
scheduleNextAlarm(context, addedAlarm, team, factory)
|
||||
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "알람 추가 동기화 실패", e)
|
||||
Log.e(TAG, "알람 추가 실패", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 알람 수정 동기화
|
||||
* DB 수정 후 기존 AlarmManager 예약 취소 후 재예약
|
||||
* 알람 수정
|
||||
* DB 수정 후 기존 예약 취소 후 재예약
|
||||
*/
|
||||
suspend fun updateAlarm(context: Context, alarm: CustomAlarm): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val repo = ShiftRepository(context)
|
||||
|
||||
// 1. 기존 AlarmManager 예약 취소
|
||||
cancelAllCustomAlarmSchedules(context, alarm.id)
|
||||
Log.d(TAG, "기존 알람 예약 취소 완료: ID=${alarm.id}")
|
||||
// 1. 기존 예약 취소
|
||||
cancelAlarm(context, alarm.id)
|
||||
Log.d(TAG, "기존 알람 취소 완료: ID=${alarm.id}")
|
||||
|
||||
// 2. DB 업데이트
|
||||
repo.updateCustomAlarm(alarm)
|
||||
@@ -97,70 +62,45 @@ object AlarmSyncManager {
|
||||
|
||||
// 3. 활성화된 알람이면 재예약
|
||||
if (alarm.isEnabled) {
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
for (i in 0 until 30) {
|
||||
val targetDate = today.plusDays(i.toLong())
|
||||
val shift = repo.getShift(targetDate,
|
||||
context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
.getString("selected_team", "A") ?: "A",
|
||||
context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
)
|
||||
|
||||
if (alarm.shiftType == "기타" || alarm.shiftType == shift) {
|
||||
scheduleCustomAlarm(
|
||||
context,
|
||||
targetDate,
|
||||
alarm.id,
|
||||
alarm.shiftType,
|
||||
alarm.time,
|
||||
alarm.soundUri,
|
||||
alarm.snoozeInterval,
|
||||
alarm.snoozeRepeat
|
||||
)
|
||||
}
|
||||
}
|
||||
val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
val team = prefs.getString("selected_team", "A") ?: "A"
|
||||
val factory = prefs.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
|
||||
scheduleNextAlarm(context, alarm, team, factory)
|
||||
Log.d(TAG, "알람 재예약 완료: ID=${alarm.id}")
|
||||
}
|
||||
|
||||
// 4. 동기화 상태 저장
|
||||
saveSyncStatus(context, "last_update_alarm", System.currentTimeMillis())
|
||||
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "알람 수정 동기화 실패", e)
|
||||
Log.e(TAG, "알람 수정 실패", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 알람 삭제 동기화
|
||||
* 알람 삭제
|
||||
* AlarmManager 예약 먼저 취소 후 DB에서 삭제
|
||||
*/
|
||||
suspend fun deleteAlarm(context: Context, alarm: CustomAlarm): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val repo = ShiftRepository(context)
|
||||
|
||||
// 1. AlarmManager 예약 취소 (DB 삭제 전에 먼저!)
|
||||
cancelAllCustomAlarmSchedules(context, alarm.id)
|
||||
cancelAlarm(context, alarm.id)
|
||||
Log.d(TAG, "알람 예약 취소 완료: ID=${alarm.id}")
|
||||
|
||||
// 2. DB에서 삭제
|
||||
val repo = ShiftRepository(context)
|
||||
repo.deleteCustomAlarm(alarm)
|
||||
Log.d(TAG, "알람 DB 삭제 완료: ID=${alarm.id}")
|
||||
|
||||
// 3. 동기화 상태 저장
|
||||
saveSyncStatus(context, "last_delete_alarm", System.currentTimeMillis())
|
||||
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "알람 삭제 동기화 실패", e)
|
||||
Log.e(TAG, "알람 삭제 실패", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 알람 토글 동기화 (활성화/비활성화)
|
||||
* 알람 토글 (활성화/비활성화)
|
||||
*/
|
||||
suspend fun toggleAlarm(context: Context, alarm: CustomAlarm, enable: Boolean): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
@@ -170,94 +110,67 @@ object AlarmSyncManager {
|
||||
if (enable) {
|
||||
// 활성화: DB 업데이트 후 예약
|
||||
repo.updateCustomAlarm(updatedAlarm)
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
for (i in 0 until 30) {
|
||||
val targetDate = today.plusDays(i.toLong())
|
||||
val shift = repo.getShift(targetDate,
|
||||
context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
.getString("selected_team", "A") ?: "A",
|
||||
context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
)
|
||||
|
||||
if (alarm.shiftType == "기타" || alarm.shiftType == shift) {
|
||||
scheduleCustomAlarm(
|
||||
context,
|
||||
targetDate,
|
||||
alarm.id,
|
||||
alarm.shiftType,
|
||||
alarm.time,
|
||||
alarm.soundUri,
|
||||
alarm.snoozeInterval,
|
||||
alarm.snoozeRepeat
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
val team = prefs.getString("selected_team", "A") ?: "A"
|
||||
val factory = prefs.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
|
||||
scheduleNextAlarm(context, updatedAlarm, team, factory)
|
||||
Log.d(TAG, "알람 활성화 완료: ID=${alarm.id}")
|
||||
} else {
|
||||
// 비활성화: 예약 취소 후 DB 업데이트
|
||||
cancelAllCustomAlarmSchedules(context, alarm.id)
|
||||
cancelAlarm(context, alarm.id)
|
||||
repo.updateCustomAlarm(updatedAlarm)
|
||||
Log.d(TAG, "알람 비활성화 완료: ID=${alarm.id}")
|
||||
}
|
||||
|
||||
saveSyncStatus(context, "last_toggle_alarm", System.currentTimeMillis())
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "알람 토글 동기화 실패", e)
|
||||
Log.e(TAG, "알람 토글 실패", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 알람 동기화 (앱 시작 시 호출)
|
||||
* 전체 알람 동기화 (앱 시작/설정 변경 시)
|
||||
* 깨끗한 상태에서 모든 활성화된 알람 재예약
|
||||
*/
|
||||
suspend fun syncAllAlarmsWithCheck(context: Context): Result<SyncResult> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
Log.d(TAG, "전체 알람 동기화 시작")
|
||||
|
||||
// 1. 기존 모든 알람 취소
|
||||
val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
val repo = ShiftRepository(context)
|
||||
val allAlarms = repo.getAllCustomAlarms()
|
||||
|
||||
// 1. 모든 기존 알람 취소
|
||||
for (alarm in allAlarms) {
|
||||
cancelAllCustomAlarmSchedules(context, alarm.id)
|
||||
cancelAlarm(context, alarm.id)
|
||||
}
|
||||
Log.d(TAG, "기존 모든 알람 취소 완료: ${allAlarms.size}개")
|
||||
|
||||
// 2. 활성화된 알람만 재예약
|
||||
val enabledAlarms = allAlarms.filter { it.isEnabled }
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
// 2. 마스터 알람이 꺼져있으면 여기서 종료
|
||||
if (!ShiftAlarmDefaults.isMasterAlarmEnabled(prefs)) {
|
||||
Log.d(TAG, "마스터 알람 꺼짐, 동기화 종료")
|
||||
return@withContext Result.success(SyncResult(
|
||||
totalAlarms = allAlarms.size,
|
||||
enabledAlarms = 0,
|
||||
scheduledAlarms = 0
|
||||
))
|
||||
}
|
||||
|
||||
// 3. 활성화된 알람만 재예약
|
||||
val team = prefs.getString("selected_team", "A") ?: "A"
|
||||
val factory = prefs.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
val enabledAlarms = allAlarms.filter { it.isEnabled }
|
||||
|
||||
var scheduledCount = 0
|
||||
for (alarm in enabledAlarms) {
|
||||
for (i in 0 until 30) {
|
||||
val targetDate = today.plusDays(i.toLong())
|
||||
val shift = repo.getShift(targetDate, team, factory)
|
||||
|
||||
if (alarm.shiftType == "기타" || alarm.shiftType == shift) {
|
||||
scheduleCustomAlarm(
|
||||
context,
|
||||
targetDate,
|
||||
alarm.id,
|
||||
alarm.shiftType,
|
||||
alarm.time,
|
||||
alarm.soundUri,
|
||||
alarm.snoozeInterval,
|
||||
alarm.snoozeRepeat
|
||||
)
|
||||
scheduledCount++
|
||||
}
|
||||
}
|
||||
scheduleNextAlarm(context, alarm, team, factory)
|
||||
scheduledCount++
|
||||
}
|
||||
|
||||
Log.d(TAG, "알람 재예약 완료: ${enabledAlarms.size}개 알람, ${scheduledCount}개 예약")
|
||||
|
||||
// 3. 동기화 상태 저장
|
||||
saveSyncStatus(context, "last_full_sync", System.currentTimeMillis())
|
||||
Log.d(TAG, "알람 재예약 완료: ${enabledAlarms.size}개 알람")
|
||||
|
||||
Result.success(SyncResult(
|
||||
totalAlarms = allAlarms.size,
|
||||
@@ -271,21 +184,77 @@ object AlarmSyncManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* 동기화 상태 저장
|
||||
* 특정 날짜 알람 스케줄링 (WorkManager에서 매일 자정 호출)
|
||||
*/
|
||||
private fun saveSyncStatus(context: Context, key: String, timestamp: Long) {
|
||||
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.putLong(key, timestamp)
|
||||
.apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* 마지막 동기화 시간 확인
|
||||
*/
|
||||
fun getLastSyncTime(context: Context, key: String): Long {
|
||||
return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
.getLong(key, 0)
|
||||
suspend fun scheduleAlarmsForDate(context: Context, date: java.time.LocalDate): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
|
||||
if (!ShiftAlarmDefaults.isMasterAlarmEnabled(prefs)) {
|
||||
return@withContext Result.success(Unit)
|
||||
}
|
||||
|
||||
val repo = ShiftRepository(context)
|
||||
val team = prefs.getString("selected_team", "A") ?: "A"
|
||||
val factory = prefs.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
val alarms = repo.getAllCustomAlarms()
|
||||
val shift = repo.getShift(date, team, factory)
|
||||
|
||||
// 해당 날짜의 기존 알람 모두 취소
|
||||
for (alarm in alarms) {
|
||||
val alarmId = getAlarmId(alarm.id, date)
|
||||
if (alarmId != -1) {
|
||||
cancelAlarmInternal(context, alarmId)
|
||||
}
|
||||
}
|
||||
|
||||
// 조건에 맞는 활성화된 알람만 재예약
|
||||
for (alarm in alarms) {
|
||||
if (!alarm.isEnabled) continue
|
||||
|
||||
if (alarm.shiftType == "기타" || alarm.shiftType == shift) {
|
||||
// 오늘 기준으로 시간이 지났는지 확인
|
||||
val now = java.time.LocalDateTime.now(SEOUL_ZONE)
|
||||
val parts = alarm.time.split(":")
|
||||
val hour = parts[0].toIntOrNull() ?: continue
|
||||
val minute = parts[1].toIntOrNull() ?: continue
|
||||
val alarmTime = java.time.LocalDateTime.of(date, java.time.LocalTime.of(hour, minute))
|
||||
|
||||
// 오늘이고 이미 지난 시간이면 예약 안함
|
||||
if (date == java.time.LocalDate.now(SEOUL_ZONE) && alarmTime.isBefore(now)) {
|
||||
continue
|
||||
}
|
||||
|
||||
val alarmId = getAlarmId(alarm.id, date)
|
||||
if (alarmId == -1) continue
|
||||
|
||||
val intent = android.content.Intent(context, AlarmReceiver::class.java).apply {
|
||||
action = "com.example.shiftalarm.ALARM_TRIGGER"
|
||||
putExtra("EXTRA_ALARM_DB_ID", alarm.id)
|
||||
putExtra("EXTRA_DATE", date.toString())
|
||||
putExtra("EXTRA_TIME", alarm.time)
|
||||
putExtra("EXTRA_SHIFT_TYPE", alarm.shiftType)
|
||||
putExtra("EXTRA_SOUND", alarm.soundUri)
|
||||
putExtra("EXTRA_SNOOZE", alarm.snoozeInterval)
|
||||
putExtra("EXTRA_SNOOZE_REPEAT", alarm.snoozeRepeat)
|
||||
}
|
||||
|
||||
val pendingIntent = android.app.PendingIntent.getBroadcast(
|
||||
context, alarmId, intent,
|
||||
android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
val triggerTime = alarmTime.atZone(SEOUL_ZONE).toInstant().toEpochMilli()
|
||||
setExactAlarm(context, triggerTime, pendingIntent)
|
||||
}
|
||||
}
|
||||
|
||||
Log.d(TAG, "${date} 알람 스케줄링 완료")
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "알람 스케줄링 실패: $date", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,201 +6,297 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
val SEOUL_ZONE: ZoneId = ZoneId.of("Asia/Seoul")
|
||||
const val TAG = "ShiftAlarm"
|
||||
|
||||
// ============================================
|
||||
// 알람 ID 생성
|
||||
// 알람 ID 생성 - 단순화: alarmId * 10000 + 날짜 기반 오프셋
|
||||
// ============================================
|
||||
fun getCustomAlarmId(date: LocalDate, uniqueId: Int): Int {
|
||||
// Combine date and a unique ID from DB to avoid collisions
|
||||
// Using (uniqueId % 1000) to keep it within a reasonable range
|
||||
return 200000000 + (date.year % 100) * 1000000 + date.monthValue * 10000 + date.dayOfMonth * 100 + (uniqueId % 100)
|
||||
fun getAlarmId(alarmDbId: Int, date: LocalDate): Int {
|
||||
// alarmDbId: 1, 2, 3...
|
||||
// 날짜 오프셋: 오늘=0, 내일=1, ... 6일 후=6 (일주일 단위로 재사용)
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
val dayOffset = java.time.temporal.ChronoUnit.DAYS.between(today, date).toInt()
|
||||
|
||||
// 범위 체크: -30일 ~ +30일 범위 내에서만 유효
|
||||
if (dayOffset < -30 || dayOffset > 30) {
|
||||
return -1 // 유효하지 않음
|
||||
}
|
||||
|
||||
// ID 생성: alarmDbId * 100 + dayOffset (음수 처리)
|
||||
// 예: alarmDbId=5, 오늘(dayOffset=0) -> 500
|
||||
// 예: alarmDbId=5, 내일(dayOffset=1) -> 501
|
||||
return alarmDbId * 100 + dayOffset + 30 // +30으로 음수 방지
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 사용자 알람 예약
|
||||
// 다음 알람 예약 (오늘 또는 내일 중 다음 발생)
|
||||
// ============================================
|
||||
fun scheduleCustomAlarm(
|
||||
context: Context,
|
||||
date: LocalDate,
|
||||
uniqueId: Int,
|
||||
shiftType: String,
|
||||
time: String,
|
||||
soundUri: String? = null,
|
||||
snoozeMin: Int = 5,
|
||||
snoozeRepeat: Int = 3
|
||||
suspend fun scheduleNextAlarm(
|
||||
context: Context,
|
||||
alarm: CustomAlarm,
|
||||
team: String,
|
||||
factory: String
|
||||
) {
|
||||
val alarmId = getCustomAlarmId(date, uniqueId)
|
||||
val label = "사용자:$shiftType"
|
||||
if (!alarm.isEnabled) {
|
||||
Log.d(TAG, "알람 비활성화됨, 예약 안함: ID=${alarm.id}")
|
||||
return
|
||||
}
|
||||
|
||||
val parts = time.split(":")
|
||||
val repo = ShiftRepository(context)
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
val now = LocalDateTime.now(SEOUL_ZONE)
|
||||
|
||||
// 시간 파싱
|
||||
val parts = alarm.time.split(":")
|
||||
if (parts.size != 2) return
|
||||
val hour = parts[0].toIntOrNull() ?: return
|
||||
val min = parts[1].toIntOrNull() ?: return
|
||||
val minute = parts[1].toIntOrNull() ?: return
|
||||
|
||||
// 오늘 날짜의 알람 시간
|
||||
val todayAlarmTime = LocalDateTime.of(today, LocalTime.of(hour, minute))
|
||||
|
||||
// 오늘 근무 확인
|
||||
val todayShift = repo.getShift(today, team, factory)
|
||||
|
||||
// 오늘 알람이 아직 안 울렸고, 근무 조건이 맞으면 오늘 예약
|
||||
val shouldRingToday = todayAlarmTime.isAfter(now) &&
|
||||
(alarm.shiftType == "기타" || alarm.shiftType == todayShift)
|
||||
|
||||
if (shouldRingToday) {
|
||||
scheduleAlarmForDate(context, alarm, today, team, factory)
|
||||
Log.d(TAG, "오늘 알람 예약: ${alarm.time} (ID=${alarm.id})")
|
||||
} else {
|
||||
// 내일 알람 예약
|
||||
val tomorrow = today.plusDays(1)
|
||||
val tomorrowShift = repo.getShift(tomorrow, team, factory)
|
||||
|
||||
if (alarm.shiftType == "기타" || alarm.shiftType == tomorrowShift) {
|
||||
scheduleAlarmForDate(context, alarm, tomorrow, team, factory)
|
||||
Log.d(TAG, "내일 알람 예약: ${alarm.time} (ID=${alarm.id})")
|
||||
} else {
|
||||
// 근무 조건이 맞지 않으면 취소만 하고 예약 안함
|
||||
cancelAlarmForDate(context, alarm.id, today)
|
||||
cancelAlarmForDate(context, alarm.id, tomorrow)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 특정 날짜 알람 예약
|
||||
// ============================================
|
||||
private suspend fun scheduleAlarmForDate(
|
||||
context: Context,
|
||||
alarm: CustomAlarm,
|
||||
date: LocalDate,
|
||||
team: String,
|
||||
factory: String
|
||||
) {
|
||||
val alarmId = getAlarmId(alarm.id, date)
|
||||
if (alarmId == -1) return
|
||||
|
||||
// 먼저 기존 알람 취소
|
||||
cancelAlarmInternal(context, alarmId)
|
||||
|
||||
val parts = alarm.time.split(":")
|
||||
val hour = parts[0].toIntOrNull() ?: return
|
||||
val minute = parts[1].toIntOrNull() ?: return
|
||||
|
||||
val targetDateTime = LocalDateTime.of(date, LocalTime.of(hour, minute))
|
||||
.withSecond(0).withNano(0)
|
||||
|
||||
val alarmTime = targetDateTime.atZone(SEOUL_ZONE).toInstant().toEpochMilli()
|
||||
|
||||
// 과거 시간이면 예약 안함
|
||||
if (alarmTime <= System.currentTimeMillis()) {
|
||||
return
|
||||
}
|
||||
|
||||
val intent = Intent(context, AlarmReceiver::class.java).apply {
|
||||
action = "com.example.shiftalarm.ALARM_TRIGGER"
|
||||
putExtra("EXTRA_SHIFT", label)
|
||||
putExtra("EXTRA_ALARM_DB_ID", alarm.id)
|
||||
putExtra("EXTRA_DATE", date.toString())
|
||||
putExtra("EXTRA_TIME", time)
|
||||
putExtra("EXTRA_ALARM_ID", alarmId)
|
||||
putExtra("EXTRA_IS_CUSTOM", true)
|
||||
putExtra("EXTRA_UNIQUE_ID", uniqueId) // DB 검증용
|
||||
putExtra("EXTRA_SOUND", soundUri)
|
||||
putExtra("EXTRA_SNOOZE", snoozeMin)
|
||||
putExtra("EXTRA_SNOOZE_REPEAT", snoozeRepeat)
|
||||
putExtra("EXTRA_TIME", alarm.time)
|
||||
putExtra("EXTRA_SHIFT_TYPE", alarm.shiftType)
|
||||
putExtra("EXTRA_SOUND", alarm.soundUri)
|
||||
putExtra("EXTRA_SNOOZE", alarm.snoozeInterval)
|
||||
putExtra("EXTRA_SNOOZE_REPEAT", alarm.snoozeRepeat)
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context, alarmId, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
val targetDateTime = LocalDateTime.of(date, LocalTime.of(hour, min))
|
||||
.withSecond(0).withNano(0)
|
||||
|
||||
val alarmTime = targetDateTime.atZone(SEOUL_ZONE).toInstant().toEpochMilli()
|
||||
|
||||
if (alarmTime > System.currentTimeMillis()) {
|
||||
setExactAlarm(context, alarmTime, pendingIntent)
|
||||
Log.d(TAG, "알람 예약 완료: $date $time (ID: $alarmId)")
|
||||
}
|
||||
|
||||
setExactAlarm(context, alarmTime, pendingIntent)
|
||||
Log.d(TAG, "알람 예약 완료: $date ${alarm.time} (AlarmID: $alarmId, DbID: ${alarm.id})")
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 알람 취소 (전체 범위)
|
||||
// 알람 취소 - 특정 알람의 모든 예약 취소
|
||||
// ============================================
|
||||
fun cancelCustomAlarm(context: Context, date: LocalDate, uniqueId: Int) {
|
||||
val alarmId = getCustomAlarmId(date, uniqueId)
|
||||
fun cancelAlarm(context: Context, alarmId: Int) {
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
|
||||
// 오늘, 내일 알람 취소 (다른 날짜는 WorkManager가 매일 재설정)
|
||||
cancelAlarmForDate(context, alarmId, today)
|
||||
cancelAlarmForDate(context, alarmId, today.plusDays(1))
|
||||
|
||||
Log.d(TAG, "알람 취소 완료: ID=$alarmId")
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 특정 날짜 알람 취소
|
||||
// ============================================
|
||||
private fun cancelAlarmForDate(context: Context, alarmDbId: Int, date: LocalDate) {
|
||||
val alarmId = getAlarmId(alarmDbId, date)
|
||||
if (alarmId == -1) return
|
||||
cancelAlarmInternal(context, alarmId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 알람의 모든 예약을 완전히 취소합니다.
|
||||
* DB에서 삭제하기 전에 반드시 호출해야 합니다.
|
||||
* 삭제한 알람이 울리는 문제를 해결하기 위해 365일치 + 과거 알람까지 모두 취소
|
||||
*/
|
||||
fun cancelAllCustomAlarmSchedules(context: Context, uniqueId: Int) {
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
// ============================================
|
||||
// 날짜에 대한 날짜 알람 취소
|
||||
// ============================================
|
||||
suspend fun cancelAlarmsForDate(context: Context, date: LocalDate) {
|
||||
val repo = ShiftRepository(context)
|
||||
val alarms = repo.getAllCustomAlarms()
|
||||
|
||||
// 1. 과거 30일치 취소 (혹시 모를 과거 예약)
|
||||
for (i in -30 until 0) {
|
||||
val targetDate = today.plusDays(i.toLong())
|
||||
cancelCustomAlarm(context, targetDate, uniqueId)
|
||||
for (alarm in alarms) {
|
||||
cancelAlarmForDate(context, alarm.id, date)
|
||||
}
|
||||
|
||||
// 2. 향후 365일치 모든 가능한 ID 취소 (1년치 완전 커버)
|
||||
for (i in 0 until 365) {
|
||||
val targetDate = today.plusDays(i.toLong())
|
||||
cancelCustomAlarm(context, targetDate, uniqueId)
|
||||
}
|
||||
|
||||
// 3. 스누즈 알람도 취소 (스누즈는 999999 ID 사용)
|
||||
cancelSnoozeAlarm(context)
|
||||
|
||||
// 4. 테스트 알람도 취소 (테스트는 888888 ID 사용)
|
||||
cancelTestAlarm(context)
|
||||
|
||||
// 5. 해당 uniqueId와 관련된 모든 가능한 PendingIntent 취소 (추가 안전장치)
|
||||
cancelAllPendingIntentsForUniqueId(context, uniqueId)
|
||||
|
||||
Log.d(TAG, "알람 예약 완전 취소 완료 (ID: $uniqueId, 범위: -30일 ~ +365일)")
|
||||
Log.d(TAG, "${date} 날짜의 모든 알람 취소 완료")
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 uniqueId에 대한 모든 가능한 PendingIntent를 취소합니다.
|
||||
* 알람 ID 생성 공식의 역연산을 통해 모든 가능성을 커버합니다.
|
||||
*/
|
||||
private fun cancelAllPendingIntentsForUniqueId(context: Context, uniqueId: Int) {
|
||||
// ============================================
|
||||
// 날짜에 대한 날짜 알람 스케줄링 (매일 자정 호출)
|
||||
// ============================================
|
||||
suspend fun scheduleAlarmsForDate(context: Context, date: LocalDate) {
|
||||
val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
|
||||
if (!ShiftAlarmDefaults.isMasterAlarmEnabled(prefs)) {
|
||||
Log.d(TAG, "마스터 알람 꺼짐, 스케줄링 중단")
|
||||
return
|
||||
}
|
||||
|
||||
val repo = ShiftRepository(context)
|
||||
val team = prefs.getString("selected_team", "A") ?: "A"
|
||||
val factory = prefs.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
|
||||
// 해당 날짜의 근무 확인
|
||||
val shift = repo.getShift(date, team, factory)
|
||||
val alarms = repo.getAllCustomAlarms()
|
||||
|
||||
// 활성화된 알람 중 근무 조건이 맞는 것만 예약
|
||||
for (alarm in alarms) {
|
||||
if (!alarm.isEnabled) continue
|
||||
|
||||
if (alarm.shiftType == "기타" || alarm.shiftType == shift) {
|
||||
scheduleAlarmForDate(context, alarm, date, team, factory)
|
||||
} else {
|
||||
// 조건 안 맞으면 취소
|
||||
cancelAlarmForDate(context, alarm.id, date)
|
||||
}
|
||||
}
|
||||
|
||||
Log.d(TAG, "${date} 날짜 알람 스케줄링 완료")
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 모든 알람 취소 (마스터 오프 시)
|
||||
// ============================================
|
||||
suspend fun cancelAllAlarms(context: Context) {
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
val repo = ShiftRepository(context)
|
||||
val alarms = repo.getAllCustomAlarms()
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
|
||||
// uniqueId % 100의 모든 가능한 값에 대해 취소 시도
|
||||
val baseId = uniqueId % 100
|
||||
for (alarm in alarms) {
|
||||
// 오늘, 내일 알람 취소
|
||||
for (dayOffset in 0..1) {
|
||||
val date = today.plusDays(dayOffset.toLong())
|
||||
val alarmId = getAlarmId(alarm.id, date)
|
||||
if (alarmId == -1) continue
|
||||
|
||||
val intent = Intent(context, AlarmReceiver::class.java).apply {
|
||||
action = "com.example.shiftalarm.ALARM_TRIGGER"
|
||||
}
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context, alarmId, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
alarmManager.cancel(pendingIntent)
|
||||
pendingIntent.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// 현재 연도 기준으로 여러 해에 걸친 가능한 ID들
|
||||
val currentYear = LocalDate.now(SEOUL_ZONE).year % 100
|
||||
val years = listOf(currentYear - 1, currentYear, currentYear + 1)
|
||||
// 스누즈 알람도 취소
|
||||
cancelSnoozeAlarm(context)
|
||||
|
||||
for (year in years) {
|
||||
if (year < 0) continue
|
||||
for (month in 1..12) {
|
||||
for (day in 1..31) {
|
||||
try {
|
||||
val alarmId = 200000000 + year * 1000000 + month * 10000 + day * 100 + baseId
|
||||
val intent = Intent(context, AlarmReceiver::class.java)
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context, alarmId, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
alarmManager.cancel(pendingIntent)
|
||||
pendingIntent.cancel()
|
||||
} catch (e: Exception) {
|
||||
// 무시 - 유효하지 않은 날짜 조합
|
||||
}
|
||||
Log.d(TAG, "모든 알람 취소 완료")
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 날짜 알람 전체 동기화 (앱 시작/설정 변경 시)
|
||||
// ============================================
|
||||
suspend fun syncAllAlarms(context: Context) {
|
||||
Log.d(TAG, "===== 알람 동기화 시작 =====")
|
||||
|
||||
val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
|
||||
if (!ShiftAlarmDefaults.isMasterAlarmEnabled(prefs)) {
|
||||
Log.d(TAG, "마스터 알람 꺼짐, 모든 알람 취소")
|
||||
cancelAllAlarms(context)
|
||||
return
|
||||
}
|
||||
|
||||
val repo = ShiftRepository(context)
|
||||
val team = prefs.getString("selected_team", "A") ?: "A"
|
||||
val factory = prefs.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
val alarms = repo.getAllCustomAlarms()
|
||||
|
||||
// 1. 모든 알람 취소 (깨끗한 상태에서 시작)
|
||||
for (alarm in alarms) {
|
||||
for (dayOffset in -1..1) { // 어제, 오늘, 내일
|
||||
val date = today.plusDays(dayOffset.toLong())
|
||||
cancelAlarmForDate(context, alarm.id, date)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 활성화된 알람 재예약
|
||||
var scheduledCount = 0
|
||||
for (alarm in alarms) {
|
||||
if (!alarm.isEnabled) continue
|
||||
|
||||
// 오늘과 내일만 예약
|
||||
for (dayOffset in 0..1) {
|
||||
val date = today.plusDays(dayOffset.toLong())
|
||||
val shift = repo.getShift(date, team, factory)
|
||||
|
||||
if (alarm.shiftType == "기타" || alarm.shiftType == shift) {
|
||||
scheduleAlarmForDate(context, alarm, date, team, factory)
|
||||
scheduledCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Log.d(TAG, "uniqueId $uniqueId 관련 모든 PendingIntent 취소 완료")
|
||||
Log.d(TAG, "===== 알람 동기화 완료: $scheduledCount 개 예약 =====")
|
||||
}
|
||||
|
||||
/**
|
||||
* 스누즈 알람 취소
|
||||
*/
|
||||
/**
|
||||
* 스누즈 알람 취소 - 모든 가능한 스누즈 ID 취소
|
||||
*/
|
||||
fun cancelSnoozeAlarm(context: Context) {
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
|
||||
// 주요 스누즈 ID들 취소
|
||||
val snoozeIds = listOf(999999, 999998, 999997, 999996, 999995)
|
||||
|
||||
for (snoozeId in snoozeIds) {
|
||||
val intent = Intent(context, AlarmReceiver::class.java).apply {
|
||||
action = "com.example.shiftalarm.SNOOZE"
|
||||
}
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context, snoozeId, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
alarmManager.cancel(pendingIntent)
|
||||
pendingIntent.cancel()
|
||||
}
|
||||
|
||||
Log.d(TAG, "스누즈 알람 취소 완료")
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 알람 취소
|
||||
*/
|
||||
private fun cancelTestAlarm(context: Context) {
|
||||
// ============================================
|
||||
// 날짜 알람 취소 (날짜 날짜)
|
||||
// ============================================
|
||||
internal fun cancelAlarmInternal(context: Context, alarmId: Int) {
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
val intent = Intent(context, AlarmReceiver::class.java).apply {
|
||||
action = "com.example.shiftalarm.ALARM_TRIGGER"
|
||||
}
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context, 888888, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
alarmManager.cancel(pendingIntent)
|
||||
pendingIntent.cancel()
|
||||
Log.d(TAG, "테스트 알람 취소 완료")
|
||||
}
|
||||
|
||||
private fun cancelAlarmInternal(context: Context, alarmId: Int) {
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
val intent = Intent(context, AlarmReceiver::class.java)
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context, alarmId, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
@@ -210,9 +306,9 @@ private fun cancelAlarmInternal(context: Context, alarmId: Int) {
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 정밀 알람 설정 (setAlarmClock 우선)
|
||||
// 정밀 알람 설정
|
||||
// ============================================
|
||||
private fun setExactAlarm(context: Context, triggerTime: Long, pendingIntent: PendingIntent) {
|
||||
internal fun setExactAlarm(context: Context, triggerTime: Long, pendingIntent: PendingIntent) {
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
@@ -221,8 +317,7 @@ private fun setExactAlarm(context: Context, triggerTime: Long, pendingIntent: Pe
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// setAlarmClock은 Doze 모드에서도 정확하게 작동하며 상단바 알람 아이콘을 활성화함 (신뢰도 최고)
|
||||
|
||||
try {
|
||||
val viewIntent = Intent(context, MainActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
@@ -234,16 +329,14 @@ private fun setExactAlarm(context: Context, triggerTime: Long, pendingIntent: Pe
|
||||
|
||||
val clockInfo = AlarmManager.AlarmClockInfo(triggerTime, viewPendingIntent)
|
||||
alarmManager.setAlarmClock(clockInfo, pendingIntent)
|
||||
Log.d(TAG, "setAlarmClock 예약 성공: ${java.util.Date(triggerTime)}")
|
||||
Log.d(TAG, "setAlarmClock 예약 성공")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "setAlarmClock 실패, fallback 사용", e)
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent)
|
||||
Log.d(TAG, "setExactAndAllowWhileIdle 예약 성공")
|
||||
} else {
|
||||
alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent)
|
||||
Log.d(TAG, "setExact 예약 성공")
|
||||
}
|
||||
} catch (e2: Exception) {
|
||||
Log.e(TAG, "모든 알람 예약 방법 실패", e2)
|
||||
@@ -252,7 +345,7 @@ private fun setExactAlarm(context: Context, triggerTime: Long, pendingIntent: Pe
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 스누즈
|
||||
// 스누즈 알람
|
||||
// ============================================
|
||||
fun scheduleSnooze(context: Context, snoozeMin: Int, soundUri: String? = null, snoozeRepeat: Int = 3) {
|
||||
val intent = Intent(context, AlarmReceiver::class.java).apply {
|
||||
@@ -262,13 +355,35 @@ fun scheduleSnooze(context: Context, snoozeMin: Int, soundUri: String? = null, s
|
||||
putExtra("EXTRA_SNOOZE", snoozeMin)
|
||||
putExtra("EXTRA_SNOOZE_REPEAT", snoozeRepeat)
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context, 999999, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
|
||||
val triggerTime = System.currentTimeMillis() + (snoozeMin * 60 * 1000)
|
||||
setExactAlarm(context, triggerTime, pendingIntent)
|
||||
Log.d(TAG, "스누즈 알람 예약: ${snoozeMin}분 후")
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 스누즈 알람 취소
|
||||
// ============================================
|
||||
fun cancelSnoozeAlarm(context: Context) {
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
|
||||
val intent = Intent(context, AlarmReceiver::class.java).apply {
|
||||
action = "com.example.shiftalarm.SNOOZE"
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context, 999999, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
alarmManager.cancel(pendingIntent)
|
||||
pendingIntent.cancel()
|
||||
Log.d(TAG, "스누즈 알람 취소")
|
||||
}
|
||||
|
||||
// ============================================
|
||||
@@ -277,74 +392,16 @@ fun scheduleSnooze(context: Context, snoozeMin: Int, soundUri: String? = null, s
|
||||
fun scheduleTestAlarm(context: Context) {
|
||||
val intent = Intent(context, AlarmReceiver::class.java).apply {
|
||||
action = "com.example.shiftalarm.ALARM_TRIGGER"
|
||||
putExtra("EXTRA_SHIFT", "테스트")
|
||||
putExtra("EXTRA_SHIFT_TYPE", "테스트")
|
||||
putExtra("EXTRA_TIME", "TEST")
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context, 888888, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
val triggerTime = System.currentTimeMillis() + 5000
|
||||
setExactAlarm(context, triggerTime, pendingIntent)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 전체 동기화 (30일치 예약)
|
||||
// ============================================
|
||||
suspend fun syncAllAlarms(context: Context) {
|
||||
Log.d(TAG, "===== 전체 알람 동기화 시작 (30일) =====")
|
||||
val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
|
||||
val repo = ShiftRepository(context)
|
||||
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
val team = prefs.getString("selected_team", "A") ?: "A"
|
||||
val factory = prefs.getString("selected_factory", "Jeonju") ?: "Jeonju"
|
||||
|
||||
// 1. 기존 알람 모두 취소 (안전장치)
|
||||
// Custom 알람의 경우 ID가 uniqueId 기반이므로 모든 가능성 있는 ID를 취소하기는 어려움.
|
||||
// 대신 AlarmManager에서 해당 PendingIntent를 정확히 취소해야 함.
|
||||
// 하지만 uniqueId를 알 수 없으므로, 모든 날짜 루프에서 취소 시도.
|
||||
|
||||
val customAlarms = repo.getAllCustomAlarms()
|
||||
|
||||
for (i in 0 until 30) {
|
||||
val targetDate = today.plusDays(i.toLong())
|
||||
// 기본 알람 ID 취소 (이제 안 쓰지만 하위 호환/청소용)
|
||||
val legacyId = 100000000 + (targetDate.year % 100) * 1000000 + targetDate.monthValue * 10000 + targetDate.dayOfMonth * 100
|
||||
cancelAlarmInternal(context, legacyId)
|
||||
|
||||
// 커스텀 알람 취소
|
||||
customAlarms.forEach { alarm ->
|
||||
cancelCustomAlarm(context, targetDate, alarm.id)
|
||||
}
|
||||
}
|
||||
|
||||
if (!ShiftAlarmDefaults.isMasterAlarmEnabled(prefs)) {
|
||||
Log.d(TAG, "마스터 알람이 꺼져 있어 예약을 중단합니다.")
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 새로운 스케줄 생성
|
||||
for (i in 0 until 30) {
|
||||
val targetDate = today.plusDays(i.toLong())
|
||||
val shift = repo.getShift(targetDate, team, factory)
|
||||
|
||||
for (alarm in customAlarms) {
|
||||
if (!alarm.isEnabled) continue
|
||||
|
||||
// 근무 연동 조건 확인
|
||||
if (alarm.shiftType == "기타" || alarm.shiftType == shift) {
|
||||
scheduleCustomAlarm(
|
||||
context,
|
||||
targetDate,
|
||||
alarm.id,
|
||||
alarm.shiftType,
|
||||
alarm.time,
|
||||
alarm.soundUri,
|
||||
alarm.snoozeInterval,
|
||||
alarm.snoozeRepeat
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Log.d(TAG, "===== 전체 알람 동기화 완료 =====")
|
||||
Log.d(TAG, "테스트 알람 예약: 5초 후")
|
||||
}
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
package com.example.shiftalarm
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
|
||||
|
||||
/**
|
||||
* 매일 자정 실행되는 알람 워커
|
||||
* 다음날의 알람을 스케줄링합니다.
|
||||
*/
|
||||
class AlarmWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
|
||||
|
||||
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
syncAllAlarms(applicationContext)
|
||||
val tomorrow = LocalDate.now(SEOUL_ZONE).plusDays(1)
|
||||
|
||||
// 다음날 알람 스케줄링
|
||||
AlarmSyncManager.scheduleAlarmsForDate(applicationContext, tomorrow)
|
||||
|
||||
// 오늘 남은 알람도 확인 (재부팅 등으로 누락됐을 수 있음)
|
||||
val today = LocalDate.now(SEOUL_ZONE)
|
||||
AlarmSyncManager.scheduleAlarmsForDate(applicationContext, today)
|
||||
|
||||
Result.success()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
android.util.Log.e("AlarmWorker", "알람 스케줄링 실패", e)
|
||||
Result.retry()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,12 +9,15 @@ import androidx.work.PeriodicWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* 부팅 완료 시 알람 복구 리시버
|
||||
*/
|
||||
class BootReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent?) {
|
||||
if (intent?.action == Intent.ACTION_BOOT_COMPLETED) {
|
||||
android.util.Log.d("ShiftAlarm", "[부팅] 기기 부팅 감지, 알람 복구 시작")
|
||||
|
||||
// 1) 즉시 1회 실행 → 당일 알람을 바로 복구
|
||||
// 즉시 1회 실행 → 당일 알람 복구
|
||||
val immediateWork = OneTimeWorkRequestBuilder<AlarmWorker>().build()
|
||||
WorkManager.getInstance(context).enqueueUniqueWork(
|
||||
"BootAlarmRestore",
|
||||
@@ -22,16 +25,25 @@ class BootReceiver : BroadcastReceiver() {
|
||||
immediateWork
|
||||
)
|
||||
|
||||
// 2) 24시간 주기 반복 워커 등록
|
||||
// 24시간 주기 반복 워커 등록 (자정에 실행)
|
||||
val periodicWork = PeriodicWorkRequestBuilder<AlarmWorker>(24, TimeUnit.HOURS)
|
||||
.setInitialDelay(calculateDelayToMidnight(), TimeUnit.MILLISECONDS)
|
||||
.build()
|
||||
|
||||
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
|
||||
"DailyShiftCheck",
|
||||
androidx.work.ExistingPeriodicWorkPolicy.KEEP,
|
||||
ExistingPeriodicWorkPolicy.KEEP,
|
||||
periodicWork
|
||||
)
|
||||
|
||||
android.util.Log.d("ShiftAlarm", "[부팅] 알람 복구 워커 등록 완료")
|
||||
}
|
||||
}
|
||||
|
||||
private fun calculateDelayToMidnight(): Long {
|
||||
val seoulZone = java.time.ZoneId.of("Asia/Seoul")
|
||||
val now = java.time.LocalDateTime.now(seoulZone)
|
||||
val midnight = now.plusDays(1).withHour(0).withMinute(5).withSecond(0) // 00:05에 실행
|
||||
return java.time.Duration.between(now, midnight).toMillis()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -451,13 +451,18 @@ class FragmentSettingsAlarm : Fragment(), SharedPreferences.OnSharedPreferenceCh
|
||||
if (android.os.Build.VERSION.SDK_INT >= 23) {
|
||||
timePicker.hour = parts[0].toInt(); timePicker.minute = parts[1].toInt()
|
||||
} else {
|
||||
timePicker.currentHour = parts[0].toInt(); timePicker.currentMinute = parts[1].toInt()
|
||||
@Suppress("DEPRECATION")
|
||||
timePicker.currentHour = parts[0].toInt()
|
||||
@Suppress("DEPRECATION")
|
||||
timePicker.currentMinute = parts[1].toInt()
|
||||
}
|
||||
|
||||
btnSelectSound.setOnClickListener {
|
||||
val intent = Intent(android.media.RingtoneManager.ACTION_RINGTONE_PICKER).apply {
|
||||
putExtra(android.media.RingtoneManager.EXTRA_RINGTONE_TYPE, android.media.RingtoneManager.TYPE_ALARM)
|
||||
putExtra(android.media.RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, if (currentDialogSoundUri != null) android.net.Uri.parse(currentDialogSoundUri) else null as android.net.Uri?)
|
||||
// 무음 선택 방지: 시스템 알람음만 선택 가능
|
||||
putExtra(android.media.RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false)
|
||||
}
|
||||
startActivityForResult(intent, 100)
|
||||
}
|
||||
@@ -485,7 +490,9 @@ class FragmentSettingsAlarm : Fragment(), SharedPreferences.OnSharedPreferenceCh
|
||||
|
||||
btnCancel.setOnClickListener { dialog.dismiss() }
|
||||
btnSave.setOnClickListener {
|
||||
@Suppress("DEPRECATION")
|
||||
val h = if (android.os.Build.VERSION.SDK_INT >= 23) timePicker.hour else timePicker.currentHour
|
||||
@Suppress("DEPRECATION")
|
||||
val m = if (android.os.Build.VERSION.SDK_INT >= 23) timePicker.minute else timePicker.currentMinute
|
||||
val time = String.format("%02d:%02d", h, m)
|
||||
|
||||
|
||||
107
docs/gitlab-wiki-guide.md
Normal file
107
docs/gitlab-wiki-guide.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# GitLab Wiki 설정 가이드
|
||||
|
||||
## 개요
|
||||
|
||||
GitLab Wiki는 저장소와 별도로 관리되며, 마크다운 파일로 작성합니다.
|
||||
|
||||
## 시작하기
|
||||
|
||||
### 1. Wiki 저장소 클론
|
||||
|
||||
```bash
|
||||
git clone git@git.webpluss.net:username/project.wiki.git
|
||||
cd project.wiki
|
||||
```
|
||||
|
||||
### 2. 마크다운 파일 작성
|
||||
|
||||
```bash
|
||||
touch my-page.md
|
||||
# 마크다운 작성 후
|
||||
git add .
|
||||
git commit -m "Add wiki page"
|
||||
git push
|
||||
```
|
||||
|
||||
## SSH 키 설정 (권장)
|
||||
|
||||
### 1. SSH 키 생성 (없는 경우)
|
||||
|
||||
```bash
|
||||
ssh-keygen -t ed25519 -C "your_email@example.com"
|
||||
```
|
||||
|
||||
### 2. GitLab에 SSH 키 추가
|
||||
|
||||
- GitLab → Settings → SSH Keys
|
||||
- `~/.ssh/id_ed25519.pub` 내용 복사해서 추가
|
||||
|
||||
### 3. remote 설정
|
||||
|
||||
```bash
|
||||
git remote set-url origin git@git.webpluss.net:username/project.git
|
||||
```
|
||||
|
||||
## HTTPS 사용 시 (토큰 방식)
|
||||
|
||||
### 1. Personal Access Token 생성
|
||||
|
||||
- GitLab → Settings → Access Tokens
|
||||
- 이름: `git_push`
|
||||
- 스코프: `api`
|
||||
- 만료일: 적절히 설정
|
||||
|
||||
### 2. 토큰으로 푸시
|
||||
|
||||
```bash
|
||||
git remote set-url origin https://username:TOKEN@git.webpluss.net/username/project.git
|
||||
git push -u origin main
|
||||
```
|
||||
|
||||
### 3. 토큰 숨기기 (보안)
|
||||
|
||||
```bash
|
||||
# URL에서 토큰 제거
|
||||
git remote set-url origin https://username@git.webpluss.net/username/project.git
|
||||
|
||||
# credential.helper로 토큰 저장
|
||||
git config credential.helper store
|
||||
|
||||
# 이후 푸시 시 토큰 자동 입력됨
|
||||
git push
|
||||
```
|
||||
|
||||
## 저장소 내 문서 폴더 방식
|
||||
|
||||
Wiki 저장소 접근이 어려운 경우, `docs/` 폴더를 사용할 수 있습니다.
|
||||
|
||||
```bash
|
||||
mkdir docs
|
||||
echo "# 프로젝트 문서" > docs/home.md
|
||||
git add docs/
|
||||
git commit -m "Add documentation"
|
||||
git push
|
||||
```
|
||||
|
||||
## 마크다운 문법
|
||||
|
||||
```markdown
|
||||
# 제목
|
||||
## 부제목
|
||||
|
||||
- 목록 项
|
||||
- [링크](url)
|
||||
|
||||
**굵게** *기울임*
|
||||
|
||||
코드:
|
||||
```javascript
|
||||
console.log('hello');
|
||||
```
|
||||
```
|
||||
|
||||
## 참고
|
||||
|
||||
- GitLab Wiki는 `.md` 파일만 지원
|
||||
- 파일명이 페이지 URL이 됨 (home.md → /home)
|
||||
- 사이드바는 GitLab이 자동으로 생성
|
||||
13
docs/home.md
Normal file
13
docs/home.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# ShiftRing 위키에 오신 것을 환영합니다
|
||||
|
||||
이곳은 프로젝트 문서를 작성하는 공간입니다.
|
||||
|
||||
## 목차
|
||||
|
||||
- [시작하기](getting-started)
|
||||
- [API 문서](api-reference)
|
||||
- [설치 방법](installation)
|
||||
|
||||
## 기여하기
|
||||
|
||||
문서 수정에 기여하고 싶으시다면 PR을 보내주세요.
|
||||
10
version.json
10
version.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"versionCode": 1119,
|
||||
"versionName": "1.1.9",
|
||||
"apkUrl": "https://git.webpluss.net/sanjeok77/ShiftRing/releases/download/v1.1.9/app.apk",
|
||||
"changelog": "v1.1.9: version.json URL 수정 (서버 연결 실패 해결)",
|
||||
"versionCode": 1124,
|
||||
"versionName": "1.2.4",
|
||||
"apkUrl": "https://git.webpluss.net/sanjeok77/ShiftRing/releases/download/v1.2.4/app.apk",
|
||||
"changelog": "v1.2.4: Deprecation 경고 수정 및 삭제 알람 버그 수정",
|
||||
"forceUpdate": false
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user