|
| 1 | +--- |
| 2 | +title: Debugging Background Tasks |
| 3 | +description: Debug and troubleshoot background tasks on Android and iOS |
| 4 | +--- |
| 5 | + |
| 6 | +# Debugging Background Tasks |
| 7 | + |
| 8 | +Background tasks can be tricky to debug since they run when your app is closed. Here's how to effectively debug and troubleshoot them on both platforms. |
| 9 | + |
| 10 | +## Enable Debug Mode |
| 11 | + |
| 12 | +Always start by enabling debug notifications: |
| 13 | + |
| 14 | +```dart |
| 15 | +Workmanager().initialize( |
| 16 | + callbackDispatcher, |
| 17 | + isInDebugMode: true, // Shows notifications when tasks execute |
| 18 | +); |
| 19 | +``` |
| 20 | + |
| 21 | +This shows system notifications whenever background tasks run, making it easy to verify execution. |
| 22 | + |
| 23 | +## Android Debugging |
| 24 | + |
| 25 | +### Job Scheduler Inspection |
| 26 | + |
| 27 | +Use ADB to inspect Android's job scheduler: |
| 28 | + |
| 29 | +```bash |
| 30 | +# View all scheduled jobs for your app |
| 31 | +adb shell dumpsys jobscheduler | grep your.package.name |
| 32 | + |
| 33 | +# View detailed job info |
| 34 | +adb shell dumpsys jobscheduler your.package.name |
| 35 | + |
| 36 | +# Force run a specific job (debug builds only) |
| 37 | +adb shell cmd jobscheduler run -f your.package.name JOB_ID |
| 38 | +``` |
| 39 | + |
| 40 | +### Monitor Job Execution |
| 41 | + |
| 42 | +```bash |
| 43 | +# Monitor job scheduler logs |
| 44 | +adb logcat | grep WorkManager |
| 45 | + |
| 46 | +# Monitor your app's background execution |
| 47 | +adb logcat | grep "your.package.name" |
| 48 | +``` |
| 49 | + |
| 50 | +### Common Android Issues |
| 51 | + |
| 52 | +**Tasks not running:** |
| 53 | +- Check battery optimization settings |
| 54 | +- Verify app is not in "App Standby" mode |
| 55 | +- Ensure device isn't in Doze mode |
| 56 | +- Check if constraints are too restrictive |
| 57 | + |
| 58 | +**Tasks running too often:** |
| 59 | +- Android enforces minimum 15-minute intervals for periodic tasks |
| 60 | +- Use appropriate constraints to limit execution |
| 61 | + |
| 62 | +### Debug Commands |
| 63 | + |
| 64 | +```bash |
| 65 | +# Check if your app is whitelisted from battery optimization |
| 66 | +adb shell dumpsys deviceidle whitelist |
| 67 | + |
| 68 | +# Check battery optimization status |
| 69 | +adb shell settings get global battery_saver_constants |
| 70 | + |
| 71 | +# Force device into idle mode (testing) |
| 72 | +adb shell dumpsys deviceidle force-idle |
| 73 | +``` |
| 74 | + |
| 75 | +## iOS Debugging |
| 76 | + |
| 77 | +### Console Logging |
| 78 | + |
| 79 | +iOS background tasks have limited execution time. Add detailed logging: |
| 80 | + |
| 81 | +```dart |
| 82 | +@pragma('vm:entry-point') |
| 83 | +void callbackDispatcher() { |
| 84 | + Workmanager().executeTask((task, inputData) async { |
| 85 | + print('[iOS BG] Task started: $task at ${DateTime.now()}'); |
| 86 | + |
| 87 | + try { |
| 88 | + // Your task logic |
| 89 | + final result = await performTask(); |
| 90 | + print('[iOS BG] Task completed successfully'); |
| 91 | + return true; |
| 92 | + } catch (e) { |
| 93 | + print('[iOS BG] Task failed: $e'); |
| 94 | + return false; |
| 95 | + } |
| 96 | + }); |
| 97 | +} |
| 98 | +``` |
| 99 | + |
| 100 | +### Xcode Debugging |
| 101 | + |
| 102 | +Use Xcode's console to trigger background tasks manually: |
| 103 | + |
| 104 | +```objc |
| 105 | +// Trigger background app refresh |
| 106 | +e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"your.task.id"] |
| 107 | + |
| 108 | +// Trigger processing task |
| 109 | +e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"your.processing.task.id"] |
| 110 | + |
| 111 | +// Force background fetch (legacy) |
| 112 | +e -l objc -- (void)[[UIApplication sharedApplication] _simulateApplicationDidEnterBackground] |
| 113 | +``` |
| 114 | +
|
| 115 | +### Monitor Scheduled Tasks |
| 116 | +
|
| 117 | +Check what tasks iOS has scheduled: |
| 118 | +
|
| 119 | +```dart |
| 120 | +// iOS 13+ only |
| 121 | +if (Platform.isIOS) { |
| 122 | + final tasks = await Workmanager().printScheduledTasks(); |
| 123 | + print('Scheduled tasks: $tasks'); |
| 124 | +} |
| 125 | +``` |
| 126 | + |
| 127 | +This prints output like: |
| 128 | +``` |
| 129 | +[BGTaskScheduler] Task Identifier: your.task.id earliestBeginDate: 2023.10.10 PM 11:10:12 |
| 130 | +[BGTaskScheduler] There are no scheduled tasks |
| 131 | +``` |
| 132 | + |
| 133 | +### Common iOS Issues |
| 134 | + |
| 135 | +**Tasks never run:** |
| 136 | +- Background App Refresh disabled in Settings |
| 137 | +- App hasn't been used recently (iOS learning algorithm) |
| 138 | +- Task identifiers don't match between Info.plist and AppDelegate |
| 139 | +- Missing BGTaskSchedulerPermittedIdentifiers in Info.plist |
| 140 | + |
| 141 | +**Tasks stop working:** |
| 142 | +- iOS battery optimization kicked in |
| 143 | +- App removed from recent apps too often |
| 144 | +- User disabled background refresh |
| 145 | +- Task taking longer than 30 seconds |
| 146 | + |
| 147 | +**Tasks run but don't complete:** |
| 148 | +- Hitting 30-second execution limit |
| 149 | +- Network requests timing out |
| 150 | +- Heavy processing blocking the thread |
| 151 | + |
| 152 | +## General Debugging Tips |
| 153 | + |
| 154 | +### Add Comprehensive Logging |
| 155 | + |
| 156 | +```dart |
| 157 | +@pragma('vm:entry-point') |
| 158 | +void callbackDispatcher() { |
| 159 | + Workmanager().executeTask((task, inputData) async { |
| 160 | + final startTime = DateTime.now(); |
| 161 | + print('🚀 Task started: $task'); |
| 162 | + print('📊 Input data: $inputData'); |
| 163 | + |
| 164 | + try { |
| 165 | + // Your task implementation |
| 166 | + final result = await performTask(task, inputData); |
| 167 | + |
| 168 | + final duration = DateTime.now().difference(startTime); |
| 169 | + print('✅ Task completed in ${duration.inSeconds}s'); |
| 170 | + |
| 171 | + return result; |
| 172 | + } catch (e, stackTrace) { |
| 173 | + final duration = DateTime.now().difference(startTime); |
| 174 | + print('❌ Task failed after ${duration.inSeconds}s: $e'); |
| 175 | + print('📋 Stack trace: $stackTrace'); |
| 176 | + |
| 177 | + return false; // Retry |
| 178 | + } |
| 179 | + }); |
| 180 | +} |
| 181 | +``` |
| 182 | + |
| 183 | +### Test Task Logic Separately |
| 184 | + |
| 185 | +Create a way to test your background logic from the UI: |
| 186 | + |
| 187 | +```dart |
| 188 | +// Add a debug button to test task logic |
| 189 | +ElevatedButton( |
| 190 | + onPressed: () async { |
| 191 | + // Test the same logic that runs in background |
| 192 | + final result = await performTask('test_task', {'debug': true}); |
| 193 | + print('Test result: $result'); |
| 194 | + }, |
| 195 | + child: Text('Test Task Logic'), |
| 196 | +) |
| 197 | +``` |
| 198 | + |
| 199 | +### Monitor Task Health |
| 200 | + |
| 201 | +Track when tasks last ran successfully: |
| 202 | + |
| 203 | +```dart |
| 204 | +Future<void> saveTaskExecutionTime(String taskName) async { |
| 205 | + final prefs = await SharedPreferences.getInstance(); |
| 206 | + await prefs.setString('${taskName}_last_run', DateTime.now().toIso8601String()); |
| 207 | +} |
| 208 | +
|
| 209 | +Future<bool> isTaskHealthy(String taskName, Duration maxAge) async { |
| 210 | + final prefs = await SharedPreferences.getInstance(); |
| 211 | + final lastRunString = prefs.getString('${taskName}_last_run'); |
| 212 | + |
| 213 | + if (lastRunString == null) return false; |
| 214 | + |
| 215 | + final lastRun = DateTime.parse(lastRunString); |
| 216 | + final age = DateTime.now().difference(lastRun); |
| 217 | + |
| 218 | + return age < maxAge; |
| 219 | +} |
| 220 | +``` |
| 221 | + |
| 222 | +## Platform-Specific Testing |
| 223 | + |
| 224 | +### Android Testing Workflow |
| 225 | + |
| 226 | +1. **Enable debug mode** and install app |
| 227 | +2. **Schedule task** and verify it appears in job scheduler |
| 228 | +3. **Put device to sleep** and wait for execution |
| 229 | +4. **Check debug notifications** to confirm execution |
| 230 | +5. **Use ADB commands** to force execution if needed |
| 231 | + |
| 232 | +### iOS Testing Workflow |
| 233 | + |
| 234 | +1. **Test on physical device** (simulator doesn't support background tasks) |
| 235 | +2. **Enable Background App Refresh** in iOS Settings |
| 236 | +3. **Use Xcode debugger** to trigger tasks immediately |
| 237 | +4. **Monitor Xcode console** for logging output |
| 238 | +5. **Check iOS Settings > Battery** for background activity |
| 239 | + |
| 240 | +## Troubleshooting Checklist |
| 241 | + |
| 242 | +**Task not scheduling:** |
| 243 | +- [ ] Workmanager initialized in main() |
| 244 | +- [ ] Task names are unique |
| 245 | +- [ ] Platform setup completed (iOS Info.plist, AppDelegate) |
| 246 | + |
| 247 | +**Task not executing:** |
| 248 | +- [ ] Debug notifications enabled |
| 249 | +- [ ] Battery optimization disabled (Android) |
| 250 | +- [ ] Background App Refresh enabled (iOS) |
| 251 | +- [ ] App used recently (iOS learning algorithm) |
| 252 | +- [ ] Constraints not too restrictive |
| 253 | + |
| 254 | +**Task executing but failing:** |
| 255 | +- [ ] Added try-catch error handling |
| 256 | +- [ ] Dependencies initialized in background isolate |
| 257 | +- [ ] Network timeouts configured appropriately |
| 258 | +- [ ] iOS 30-second limit respected |
| 259 | + |
| 260 | +**Performance issues:** |
| 261 | +- [ ] Task logic optimized for background execution |
| 262 | +- [ ] Heavy processing split into smaller chunks |
| 263 | +- [ ] Database operations use appropriate batch sizes |
| 264 | +- [ ] Network requests have reasonable timeouts |
| 265 | + |
| 266 | +Remember: Background task execution is controlled by the operating system and is never guaranteed. Always design your app to work gracefully when background tasks don't run as expected. |
0 commit comments