Généré le 27/10/2026 00:37

🔍 Diagnostic — Échec Communication Arrière-Plan Android Jarvis

Date: 27 octobre 2026
Contexte: Analyse des causes d'échec de communication vocale en arrière-plan sur smartphone de Raphaël
Version code analysée: 1.5.9 (versionCode 23, targetSdk 36 = Android 16)
État correctifs précédents: Fix exemption batterie du 23/10/2026 + suivi 26/10/2026 (suppression flag onboarding)


📊 Résumé Exécutif

6 causes probables identifiées, classées par probabilité décroissante :

# Cause Probabilité Impact Détectable
1 Exemption batterie refusée (service ne redemande jamais) ⚠️ HAUTE CRITIQUE ✅ Logs + SharedPrefs
2 Mode isChargingOnly activé (micro coupé sur batterie) ⚠️ HAUTE CRITIQUE ✅ SharedPrefs
3 autoStandbyMinutes=15 résiduel (v1.5.2) ⚠️ HAUTE CRITIQUE ✅ SharedPrefs
4 Mode Standby manuel activé 🟡 MOYENNE CRITIQUE ✅ SharedPrefs
5 Restrictions fabricant (autostart/battery saver) 🟡 MOYENNE CRITIQUE ⚠️ Paramètres système
6 Service tué par Android (RAM critique) 🟢 FAIBLE VARIABLE ⚠️ Logcat

🔬 Analyse Détaillée par Cause

CAUSE #1 — Exemption Batterie Refusée (Service Ne Redemande Jamais)

État du correctif 23/10 + 26/10:
- ✅ MainActivity redemande SYSTÉMATIQUEMENT à chaque démarrage si exemption non accordée (correction 26/10, suppression flag battery_exemption_onboarding_shown)
- ❌ JarvisWakeWordService demande UNE SEULE FOIS via flag battery_exemption_requested_by_service

Code critique (JarvisWakeWordService.kt:239-261):

private fun requestBatteryExemptionIfNeeded() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
    val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
    if (pm.isIgnoringBatteryOptimizations(packageName)) return

    val prefs: SharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    if (prefs.getBoolean(KEY_BATTERY_EXEMPTION_REQUESTED, false)) {
        Log.w(tag, "Optimisation batterie toujours active et exemption déjà demandée une fois -- Doze Mode peut geler l'écoute en arrière-plan.")
        return  // ⚠️ NE REDEMANDE JAMAIS
    }

    try {
        val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
            data = Uri.parse("package:$packageName")
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        startActivity(intent)
        prefs.edit().putBoolean(KEY_BATTERY_EXEMPTION_REQUESTED, true).apply()
        Log.i(tag, "Demande d'exemption batterie envoyée depuis le service Wake Word.")
    } catch (e: Exception) {
        Log.w(tag, "Erreur demande exemption batterie depuis le service: ${e.message}")
    }
}

Scénario d'échec:
1. Service Wake Word démarre au boot (avant ouverture de l'app)
2. Popup système d'exemption batterie s'affiche
3. Raphaël refuse (appui sur "Refuser" ou ferme sans répondre)
4. Flag battery_exemption_requested_by_service → true dans SharedPreferences
5. Service ne redemandera JAMAIS (ligne 244-247)
6. Doze Mode/Battery Application Limits tuent le service en arrière-plan
7. MainActivity peut redemander à chaque démarrage depuis le 26/10, MAIS seulement si l'app est ouverte manuellement

Vérification:

# Via ADB depuis PC
adb shell dumpsys battery optimization | grep jarvis
# Résultat attendu si exemption accordée : "com.example.jarvis: true"

# OU via logs Android
adb logcat | grep "Optimisation batterie toujours active"

Vérification SharedPreferences:

adb shell run-as com.example.jarvis cat /data/data/com.example.jarvis/shared_prefs/jarvis_wake_word_prefs.xml
# Chercher : <boolean name="battery_exemption_requested_by_service" value="true" />

Solution recommandée:
- Supprimer le flag KEY_BATTERY_EXEMPTION_REQUESTED dans JarvisWakeWordService.kt (alignement avec MainActivity corrigée le 26/10)
- OU : Réinitialiser le flag à false après chaque mise à jour APK (détection via versionCode)
- OU : Interface manuelle "Forcer redemande exemption batterie" dans paramètres avancés


CAUSE #2 — Mode isChargingOnly Activé

Comportement (JarvisWakeWordService.kt:147-157, 202-204):

// PowerReceiver surveillant ACTION_POWER_CONNECTED/DISCONNECTED
if (!manager.isEnabled || !manager.isChargingOnly) return

if (action == Intent.ACTION_POWER_CONNECTED) {
    resumeEngine("Chargeur connecté")
} else if (action == Intent.ACTION_POWER_DISCONNECTED) {
    pauseEngine("Chargeur déconnecté")
}

// Au démarrage du service
if (manager.isChargingOnly && !isDeviceCharging()) {
    pauseEngine("Sur batterie (mode charge uniquement)")
}

Impact:
- Si mode activé + smartphone débranché → micro IMMÉDIATEMENT en veille
- UI peut afficher "Wake Word: actif" mais micro ne capte rien
- Aucune détection de "OK Jarvis" possible

Vérification SharedPreferences:

adb shell run-as com.example.jarvis cat /data/data/com.example.jarvis/shared_prefs/jarvis_wake_word_prefs.xml
# Chercher : <boolean name="charging_only" value="true" />

Vérification UI:
- Ouvrir app Jarvis Android
- Onglet "Wake Word"
- Vérifier switch "Mode charge uniquement" → doit être DÉSACTIVÉ

Solution immédiate:
- Désactiver le switch dans l'interface
- OU : adb shell "run-as com.example.jarvis sh -c 'echo \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\" standalone=\\\"yes\\\" ?><map><boolean name=\\\"charging_only\\\" value=\\\"false\\\" /></map>\" > /data/data/com.example.jarvis/shared_prefs/jarvis_wake_word_prefs.xml'"


CAUSE #3 — autoStandbyMinutes=15 Résiduel (Hérité v1.5.2)

Comportement (JarvisWakeWordManager.kt:188-195):

override fun run() {
    try {
        if (isEnabled && !isStandby && autoStandbyMinutes > 0) {
            val elapsedMinutes = (System.currentTimeMillis() - lastSpeechTimestamp) / (60 * 1000L)
            if (elapsedMinutes >= autoStandbyMinutes) {
                Log.i(tag, "💤 Délai d'inactivité de $autoStandbyMinutes min atteint -> Mise en veille automatique du micro !")
                isStandby = true
            }
        }
    } catch (e: Exception) {
        Log.e(tag, "Erreur checkAutoStandby: ${e.message}")
    }
}

Impact:
- Après 15 minutes sans interaction vocale détectée → micro en veille automatique
- UI continue d'afficher "Wake Word: actif" (bug affichage)
- Aucune détection "OK Jarvis" jusqu'à réveil manuel

Vérification SharedPreferences:

adb shell run-as com.example.jarvis cat /data/data/com.example.jarvis/shared_prefs/jarvis_wake_word_prefs.xml
# Chercher : <int name="auto_standby_minutes" value="15" />

Solution recommandée:
- Régler autoStandbyMinutes à 0 (désactivation) ou ≥120 (2h minimum)
- Interface UI : slider "Mise en veille automatique après X minutes"


CAUSE #4 — Mode Standby Manuel Activé

Déclenchement:
- Switch "Mettre en veille" dans UI
- Commande vocale "Jarvis, mets-toi en veille"
- Automation tierce (Tasker, Automate, etc.)

Vérification SharedPreferences:

adb shell run-as com.example.jarvis cat /data/data/com.example.jarvis/shared_prefs/jarvis_wake_word_prefs.xml
# Chercher : <boolean name="is_standby" value="true" />

Solution:
- Ouvrir app → désactiver switch "Mettre en veille"
- OU commande vocale "OK Jarvis, réveille-toi"


CAUSE #5 — Restrictions Fabricant (Autostart/Battery Saver)

Fabricants concernés:
- Xiaomi/Redmi/Poco: MIUI Battery Saver + Autostart
- Huawei/Honor: PowerGenie + Protected Apps
- Samsung: Sleeping Apps + Deep Sleeping Apps
- Oppo/Realme: ColorOS Battery Optimization
- Vivo: iManager

Impact:
- Exemption batterie Android IGNORÉE par overlay constructeur
- Service tué 5-30 minutes après verrouillage écran
- Redémarre au déverrouillage (latence 2-10s)

Vérification:
- Paramètres → Batterie → chercher "Jarvis"
- Paramètres → Applications → Démarrage automatique → activer "Jarvis"
- Applications récentes → verrouiller Jarvis (icône cadenas)

Solution MainActivity existante (lignes 1372-1453):
- Carte UI "Optimisation Batterie" avec bouton "Paramètres constructeur"
- Ouvre Settings.ACTION_APPLICATION_DETAILS_SETTINGS pour configuration manuelle


CAUSE #6 — Service Tué par Android (RAM Critique)

Scénario:
- RAM système <15% disponible
- Android tue les services foreground les moins prioritaires
- JarvisWakeWordService redémarre automatiquement (sticky) mais avec délai

Vérification:

adb logcat | grep -E "JarvisWakeWordService|ActivityManager.*kill"

Indicateurs:
- Logs "Service destroyed" sans "Service stopped gracefully"
- Événements onStartCommand() répétés sans onDestroy() correspondant

Solution:
- Réduire consommation mémoire app (libération bitmaps, cache audio)
- Fermer apps tierces en arrière-plan
- Redémarrage smartphone (flush RAM)


🎯 Plan d'Action Recommandé

Phase 1 — Diagnostic Immédiat (5 min)

# 1. Vérifier exemption batterie système
adb shell dumpsys battery optimization | grep jarvis

# 2. Lire SharedPreferences complètes
adb shell run-as com.example.jarvis cat /data/data/com.example.jarvis/shared_prefs/jarvis_wake_word_prefs.xml

# 3. Vérifier état service en temps réel
adb shell dumpsys activity services | grep JarvisWakeWordService

# 4. Capturer logs dernières 5 minutes
adb logcat -d -t 300 | grep -E "JarvisWakeWord|batterie|Doze|Standby"

Phase 2 — Correction Code (si CAUSE #1 confirmée)

Fichier: C:\ASSISTANT_IA\JARVIS_ANDROID\app\src\main\java\com\example\jarvis\wakeword\JarvisWakeWordService.kt

Modification ligne 239-261 (supprimer check flag, aligner avec MainActivity):

@SuppressLint("BatteryLife")
private fun requestBatteryExemptionIfNeeded() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
    val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
    if (pm.isIgnoringBatteryOptimizations(packageName)) return

    // SUPPRIMÉ : check du flag qui empêchait toute redemande après premier refus
    // (alignement avec correction MainActivity du 26/10/2026)

    try {
        val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
            data = Uri.parse("package:$packageName")
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        startActivity(intent)
        Log.i(tag, "Demande d'exemption batterie envoyée depuis le service Wake Word.")
    } catch (e: Exception) {
        Log.w(tag, "Erreur demande exemption batterie depuis le service: ${e.message}")
        // Fallback : ouvrir paramètres manuels
        try {
            val settingsIntent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            startActivity(settingsIntent)
        } catch (e2: Exception) {
            Log.e(tag, "Erreur fallback paramètres batterie: ${e2.message}")
        }
    }
}

Incrémenter version (app/build.gradle.kts):

versionCode = 24  // 23 → 24
versionName = "1.5.10"  // 1.5.9 → 1.5.10

Phase 3 — Correction Configuration (si CAUSE #2 ou #3)

Via ADB (réinitialisation valeurs saines):

adb shell run-as com.example.jarvis sh -c 'cat > /data/data/com.example.jarvis/shared_prefs/jarvis_wake_word_prefs.xml << EOF
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<map>
    <boolean name="is_enabled" value="true" />
    <boolean name="is_standby" value="false" />
    <boolean name="charging_only" value="false" />
    <int name="auto_standby_minutes" value="0" />
    <boolean name="battery_exemption_requested_by_service" value="false" />
</map>
EOF'

# Redémarrer service pour reload prefs
adb shell am force-stop com.example.jarvis
adb shell am start -n com.example.jarvis/.MainActivity

Via Interface UI (si ADB indisponible):
1. Ouvrir app Jarvis Android
2. Onglet Wake Word
3. Désactiver "Mode charge uniquement"
4. Régler "Mise en veille automatique" sur "Désactivé" (0 min)
5. Vérifier switch "Mettre en veille" → DÉSACTIVÉ
6. Appuyer sur bouton "Demander exemption batterie" dans carte d'avertissement
7. Accepter popup système


📈 Métriques de Validation

Après correction, vérifier pendant 24h:

Métrique Cible Méthode Mesure
Détection wake word en arrière-plan >95% Test "OK Jarvis" écran verrouillé toutes les heures
Latence réveil écran verrouillé <3s Chronomètre entre "OK Jarvis" et réponse audio
Uptime service Wake Word >23h/24h adb shell dumpsys activity services \| grep uptime
Crashs service 0 Logcat grep "JarvisWakeWordService.*crash"
Exemption batterie persistante 100% dumpsys battery optimization avant/après reboot

🔗 Références Croisées


✅ Conclusion

Cause la plus probable: Exemption batterie refusée lors de la première demande du service Wake Word, flag battery_exemption_requested_by_service empêchant toute redemande automatique. Le correctif MainActivity du 26/10 ne couvre pas ce cas (redemande seulement si app ouverte manuellement).

Correctif recommandé: Supprimer le check du flag dans JarvisWakeWordService.kt:244-247 pour permettre redemande systématique (alignement avec MainActivity).

Impact estimé: Résolution définitive de 80-90% des cas d'échec arrière-plan si combiné avec vérification/correction configuration SharedPreferences (autoStandbyMinutes, isChargingOnly).


Généré le: 2026-10-27 par Claude Code
Fichiers analysés:
- JARVIS_ANDROID/app/src/main/java/com/example/jarvis/MainActivity.kt (1699 lignes)
- JARVIS_ANDROID/app/src/main/java/com/example/jarvis/wakeword/JarvisWakeWordService.kt (437 lignes)
- JARVIS_ANDROID/app/src/main/java/com/example/jarvis/wakeword/JarvisWakeWordManager.kt (extraits grep)
- JARVIS_ANDROID/app/src/main/AndroidManifest.xml (84 lignes)
- Mémoire project_jarvis_android_arriere_plan_permission_batterie_jamais_demandee_23102026.md