Repository navigation
Impedir loop de alarm clock e try-catch no attachForegroundTask #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
25e8ad8
docs: documenta workarounds de OEM e divergencias do upstream
JCPistori 60eaa50
fix: limita o loop de auto-restart do foreground service
JCPistori ec16126
fix: garante o teardown do service quando o reattach de OEM falha
JCPistori 6d0dc0c
doc: simplificação de comentários
JCPistori File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
87 changes: 87 additions & 0 deletions
87
android/src/main/kotlin/com/pravera/flutter_foreground_task/service/RestartBudget.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| package com.pravera.flutter_foreground_task.service | ||
|
|
||
| import android.content.Context | ||
| import android.util.Log | ||
| import com.pravera.flutter_foreground_task.PreferencesKey as PrefsKey | ||
|
|
||
| /** | ||
| * Orçamento de reinícios automáticos do foreground service. | ||
| * | ||
| * Utilizado para controlar o ciclo "onDestroy -> setRestartAlarm(5s) -> RestartReceiver -> | ||
| * startForegroundService -> startForeground() -> stopForegroundService -> | ||
| * onDestroy" que se repete indefinidamente a cada 5 segundos para tentar iniciar o | ||
| * serviço novamente. | ||
| * | ||
| * Aqui cada tentativa consome uma fatia de um orçamento com backoff crescente e | ||
| * teto. O contador deve zerar quando o servico volta ao foreground com sucesso, | ||
| * quando o app pede um start explicito, ou quando a janela de observação expira. | ||
| */ | ||
| object RestartBudget { | ||
| private val TAG = RestartBudget::class.java.simpleName | ||
|
|
||
| /** Atraso de cada tentativa, em ms. */ | ||
| private val BACKOFF_DELAYS = intArrayOf( | ||
| 5_000, // 5 s | ||
| 30_000, // 30 s | ||
| 120_000, // 2 min | ||
| 600_000, // 10 min | ||
| 1_800_000 // 30 min | ||
| ) | ||
|
|
||
| /** Passada esta janela sem nenhuma tentativa, o orçamento volta ao cheio. */ | ||
| private const val WINDOW_MILLIS = 60 * 60 * 1000L // 1h | ||
|
|
||
| /** | ||
| * Consome uma tentativa e devolve o atraso a usar no alarme, ou null quando o | ||
| * orçamento acabou -- nesse caso o chamador NÃO deve agendar alarme algum. | ||
| * | ||
| * @param firstAttemptDelayMillis atraso da primeira tentativa da janela. Existe | ||
| * porque o onTaskRemoved quer reagir mais rapido (1s) que o onDestroy (5s). | ||
| */ | ||
| fun consume(context: Context, firstAttemptDelayMillis: Int = BACKOFF_DELAYS[0]): Int? { | ||
| val prefs = context.getSharedPreferences(PrefsKey.RESTART_BUDGET_PREFS, Context.MODE_PRIVATE) | ||
| val now = System.currentTimeMillis() | ||
|
|
||
| val windowStart = prefs.getLong(PrefsKey.RESTART_WINDOW_START, 0L) | ||
| var attempts = prefs.getInt(PrefsKey.RESTART_ATTEMPT_COUNT, 0) | ||
|
|
||
| // Janela expirada ou primeira tentativa: recomeça o orçamento. | ||
| val isNewWindow = windowStart == 0L || (now - windowStart) > WINDOW_MILLIS | ||
| if (isNewWindow) { | ||
| attempts = 0 | ||
| } | ||
|
|
||
| if (attempts >= BACKOFF_DELAYS.size) { | ||
| Log.e(TAG, "Auto-restart budget exhausted (${BACKOFF_DELAYS.size} attempts). " + | ||
| "No further restart alarm will be scheduled until the service starts " + | ||
| "successfully or ${WINDOW_MILLIS / 60000} minutes elapse.") | ||
| return null | ||
| } | ||
|
|
||
| val delay = if (attempts == 0) firstAttemptDelayMillis else BACKOFF_DELAYS[attempts] | ||
|
|
||
| with(prefs.edit()) { | ||
| putInt(PrefsKey.RESTART_ATTEMPT_COUNT, attempts + 1) | ||
| putLong(PrefsKey.RESTART_WINDOW_START, if (isNewWindow) now else windowStart) | ||
| commit() | ||
| } | ||
|
|
||
| Log.w(TAG, "Auto-restart attempt ${attempts + 1}/${BACKOFF_DELAYS.size} scheduled in ${delay}ms.") | ||
| return delay | ||
| } | ||
|
|
||
| /** Zera o orçamento. Chamar quando o serviço voltou a rodar em foreground. */ | ||
| fun reset(context: Context) { | ||
| val prefs = context.getSharedPreferences(PrefsKey.RESTART_BUDGET_PREFS, Context.MODE_PRIVATE) | ||
| if (prefs.getInt(PrefsKey.RESTART_ATTEMPT_COUNT, 0) == 0) { | ||
| return | ||
| } | ||
|
|
||
| with(prefs.edit()) { | ||
| remove(PrefsKey.RESTART_ATTEMPT_COUNT) | ||
| remove(PrefsKey.RESTART_WINDOW_START) | ||
| commit() | ||
| } | ||
| Log.i(TAG, "Auto-restart budget reset.") | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit (Performance) —
commit()é síncrono e bloqueia a thread principal (chamado emonDestroy/onTaskRemoved, caminhos sensíveis a ANR). Se a durabilidade imediata não for estritamente necessária (o alarme é local, não lê os prefs de outro processo),apply()evita o I/O bloqueante. Se a escolha foi deliberada para garantir que o contador sobreviva a um kill do processo logo após, vale um comentário explicando — hoje não é óbvio pra quem for mexer depois.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
O apply() enfileira a escrita, que ainda vai ocorrer na thread principal dependendo do ciclo de vida