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

Diagnostic Échec Communication Arrière-Plan Android Jarvis

Date : 2026-10-27
Version analysée : 1.5.9 (versionCode 23, targetSdk 36 = Android 16)
Analyste : Claude Code (Agent Antigravity Secours)


Résumé Exécutif

Conclusion : Aucun bug de code détecté. Trois facteurs de configuration résiduelle bloquent la communication en arrière-plan :

  1. autoStandbyMinutes=15 (hérité v1.5.2) → coupe micro après 15 min inactivité
  2. Mode isChargingOnly activé → coupe micro dès débranchement secteur
  3. Exemption batterie refusée ou perdue → Doze Mode gèle les services malgré WakeLocks

Architecture des Services (Conforme)

✅ JarvisWakeWordService

✅ JarvisVoiceService


🔴 Facteurs Bloquants Identifiés

1. autoStandbyMinutes Résiduel

Fichier : JarvisWakeWordManager.kt:190-193

if (isEnabled && !isStandby && autoStandbyMinutes > 0) {
    val elapsedMinutes = (System.currentTimeMillis() - lastActivityTimestamp) / 60_000
    if (elapsedMinutes >= autoStandbyMinutes) {
        Log.i(tag, "💤 Délai d'inactivité de $autoStandbyMinutes min atteint -> Mise en veille automatique du micro !")

Comportement :
- Timer déclenché toutes les 10 secondes
- Si aucune activité vocale pendant autoStandbyMinutes → appelle enterStandby()
- enterStandby() → pauseEngine() → micro coupé + WakeLock relâché + Doze Mode autorisé

Valeur résiduelle connue : 15 minutes (hérité v1.5.2, documenté dans mémoire 23/10)

Impact :
- ✅ UI affiche "Jarvis actif"
- ❌ Micro réellement coupé après 15 min
- ❌ Aucun indicateur visuel de cette veille auto

Localisation config : SharedPreferences (probablement jarvis_wake_word_prefs ou default)


2. Mode isChargingOnly

Fichier : JarvisWakeWordService.kt:145-159

private val powerReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val action = intent?.action ?: return
        val manager = JarvisWakeWordManager.getInstance(this@JarvisWakeWordService)
        if (!manager.isEnabled || !manager.isChargingOnly) return

        if (action == Intent.ACTION_POWER_CONNECTED) {
            Log.i(tag, "🔌 Smartphone branché sur secteur -> Réveil automatique de l'écoute !")
            resumeEngine()
        } else if (action == Intent.ACTION_POWER_DISCONNECTED) {
            Log.i(tag, "🔋 Smartphone sur batterie -> Mise en veille automatique (mode chargeur actif) !")
            pauseEngine("Sur batterie")
        }
    }
}

Comportement :
- Si isChargingOnly == true → écoute active UNIQUEMENT sur secteur
- Dès ACTION_POWER_DISCONNECTED → pauseEngine("Sur batterie")
- Notification affiche "🌙 En veille (Micro 100% coupé — Sur batterie)"

Impact :
- Conçu pour économie batterie maximale
- Incompatible avec usage nomade (poche, déplacements)

Localisation config : JarvisWakeWordManager SharedPreferences


3. Exemption Batterie Non Accordée

Contexte Android :
- Doze Mode (API 23+) gèle périodiquement les apps non exemptées
- WakeLocks sont "retenus mais ignorés" pendant fenêtres Doze si isIgnoringBatteryOptimizations == false
- Documentation officielle Android confirme ce comportement

Implémentation actuelle :

MainActivity (onboarding automatique)

// Ligne 411-414
if (!isBatteryIgnoredState.value) {
    requestBatteryOptimizationExemption()
}

JarvisWakeWordService (auto-trigger service)

// Lignes 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
    }

    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}")
    }
}

⚠️ Limitation critique :
- Le service demande UNE SEULE FOIS
- Si utilisateur refuse au popup système → flag mis à true quand même
- Ne redemandera plus JAMAIS automatiquement
- Seul recours : carte manuelle dans MainActivity

Impact si refusée :
- Doze Mode intervient après ~30 min écran éteint (variable selon fabricant)
- Services gelés périodiquement (fenêtres maintenance)
- WakeLocks/WifiLock ignorés pendant gel
- Liaison réseau coupée → perte audio bidirectionnelle


📋 Plan de Vérification (Actions Immédiates)

Étape 1 : Vérifier SharedPreferences Android

# Depuis ADB (smartphone connecté USB)
adb shell
run-as com.example.jarvis
cd shared_prefs
cat jarvis_wake_word_prefs.xml
cat com.example.jarvis_preferences.xml

Chercher :
- <int name="autoStandbyMinutes" value="?" />
- <boolean name="isChargingOnly" value="?" />
- <boolean name="battery_exemption_requested_by_service" value="?" />
- <boolean name="battery_exemption_onboarding_shown" value="?" />

Étape 2 : Vérifier Exemption Batterie Système

# Depuis ADB
adb shell dumpsys deviceidle whitelist
# Chercher com.example.jarvis dans la liste

# OU depuis smartphone directement
Paramètres → Batterie → Optimisation batterie → Afficher toutes les apps → Chercher "JARVIS"
# Statut doit être "Non optimisée" ou "Désactivé"

Étape 3 : Capturer Logs Doze Mode

# Activer logs verbeux Doze
adb shell dumpsys deviceidle enable

# Capturer logs pendant transition écran éteint → Doze
adb logcat -v time *:W | grep -E "(JarvisWakeWordService|JarvisVoiceService|DeviceIdle|Doze)"

# Chercher :
# - "Transition Doze Mode détectée : isDeviceIdleMode=true"
# - "WakeLock relâché par l'OS pendant Doze"
# - "Optimisation batterie toujours active et exemption déjà demandée"

Étape 4 : Test Forcé Doze Mode

# Forcer entrée Doze (smartphone débranché, écran éteint)
adb shell dumpsys battery unplug
adb shell dumpsys deviceidle step
adb shell dumpsys deviceidle step
adb shell dumpsys deviceidle step
# Répéter jusqu'à "STATE_IDLE"

# Tester communication vocale pendant Doze forcé
# Si coupure → exemption batterie absente confirmée

🛠️ Solutions Recommandées

Solution Immédiate (Configuration)

Action : Réinitialiser SharedPreferences problématiques

// Depuis MainActivity ou outil développeur
val prefs = getSharedPreferences("jarvis_wake_word_prefs", Context.MODE_PRIVATE)
prefs.edit().apply {
    putInt("autoStandbyMinutes", 0)  // 0 = désactivé
    putBoolean("isChargingOnly", false)
    apply()
}

// Redémarrer service
JarvisWakeWordService.stop(this)
JarvisWakeWordService.start(this)

OU depuis ADB :

adb shell
run-as com.example.jarvis
cd shared_prefs
# Éditer manuellement XML ou supprimer pour reset
rm jarvis_wake_word_prefs.xml

Solution Exemption Batterie

Si exemption refusée :
1. Ouvrir l'app Jarvis
2. Carte d'avertissement accueil → bouton "Autoriser"
3. OU manuellement : Paramètres → Batterie → Optimisation batterie → JARVIS → "Ne pas optimiser"

Si popup jamais apparu :
- Vérifier logs pour exception ligne 259 de JarvisWakeWordService
- Permission REQUEST_IGNORE_BATTERY_OPTIMIZATIONS déclarée (✅ confirmé AndroidManifest.xml ligne 14)

Amélioration Code Recommandée

Problème : Demande unique du service trop permissive

Solution : Ajouter vérification périodique SANS popup harcelant

// Dans JarvisWakeWordService.onStartCommand (avant resumeEngine)
private fun verifyBatteryExemptionSilent() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
    val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
    if (!pm.isIgnoringBatteryOptimizations(packageName)) {
        // Logger + envoyer notification discrète (pas popup système)
        Log.e(tag, "⚠️ ALERTE : Exemption batterie ABSENTE - Doze Mode gelera le service !")
        // Notification persistante CRITIQUE invitant à ouvrir MainActivity
        showCriticalBatteryExemptionWarning()
    }
}

📊 Tableau Comparatif États Service

Configuration autoStandbyMinutes isChargingOnly Exemption Batterie Comportement Attendu
Optimal 0 (désactivé) false Accordée Écoute continue 24/7
Résiduel v1.5.2 15 false Accordée ❌ Coupe après 15 min inactivité
Économie batterie 0 true Accordée ❌ Coupe dès débranchement
Sans exemption 0 false Refusée ❌ Gelé par Doze après ~30 min écran éteint
Pire cas 15 true Refusée ❌ Triple blocage (inactivité + batterie + Doze)

🔗 Références Croisées


Prochaines Étapes

  1. Raphaël : Exécuter plan de vérification (ADB dump SharedPreferences + statut exemption)
  2. Claude/Antigravity : Analyser résultats et appliquer corrections config
  3. Si config OK : Activer logs verbeux et capturer transition Doze réelle
  4. Livrable final : Script de diagnostic automatisé + reset config one-click

Généré le : 2026-10-27
Agent : Claude Code (Antigravity Secours)
Fichiers analysés : 4 (MainActivity.kt, JarvisWakeWordService.kt, JarvisVoiceService.kt, AndroidManifest.xml)