Skip to content

Commit 1dcb6ac

Browse files
committed
fix: final docs.page improvements and debugging guide
- Removed badges from docs.page index (cleaner look) - Fixed all domain references from hypothetical subdomain to actual docs.page URLs - Added comprehensive debugging page with Android job scheduler and iOS console debugging - Updated sidebar navigation to include debugging section - Made GitHub README links clearer with arrow indicators - Enhanced example README documentation link
1 parent d53ec07 commit 1dcb6ac

File tree

5 files changed

+321
-16
lines changed

5 files changed

+321
-16
lines changed

README.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Execute Dart code in the background, even when your app is closed. Perfect for d
1111

1212
## 📖 Full Documentation
1313

14-
**Visit our comprehensive documentation site:** https://docs.workmanager.dev
14+
**[Visit our comprehensive documentation ](https://docs.page/fluttercommunity/flutter_workmanager)**
1515

1616
## ⚡ Quick Start
1717

@@ -54,10 +54,10 @@ void main() {
5454

5555
| Use Case | Documentation |
5656
|----------|---------------|
57-
| **Sync data from API** | [Data Sync Guide](https://docs.workmanager.dev/usecases/data-sync) |
58-
| **Upload files in background** | [File Upload Guide](https://docs.workmanager.dev/usecases/upload-files) |
59-
| **Clean up old data** | [Cleanup Guide](https://docs.workmanager.dev/usecases/periodic-cleanup) |
60-
| **Fetch notifications** | [Notifications Guide](https://docs.workmanager.dev/usecases/fetch-notifications) |
57+
| **Sync data from API** | [Data Sync Guide](https://docs.page/fluttercommunity/flutter_workmanager/usecases/data-sync) |
58+
| **Upload files in background** | [File Upload Guide](https://docs.page/fluttercommunity/flutter_workmanager/usecases/upload-files) |
59+
| **Clean up old data** | [Cleanup Guide](https://docs.page/fluttercommunity/flutter_workmanager/usecases/periodic-cleanup) |
60+
| **Fetch notifications** | [Notifications Guide](https://docs.page/fluttercommunity/flutter_workmanager/usecases/fetch-notifications) |
6161

6262
## 🏗️ Architecture
6363

@@ -71,9 +71,9 @@ All packages are automatically included when you add `workmanager` to pubspec.ya
7171

7272
## 🐛 Issues & Support
7373

74-
- **Bug reports**: [GitHub Issues](https://github.com/fluttercommunity/flutter_workmanager/issues)
75-
- **Questions**: [GitHub Discussions](https://github.com/fluttercommunity/flutter_workmanager/discussions)
76-
- **Documentation**: https://docs.workmanager.dev
74+
- **Bug reports**: [GitHub Issues](https://github.com/fluttercommunity/flutter_workmanager/issues)
75+
- **Questions**: [GitHub Discussions](https://github.com/fluttercommunity/flutter_workmanager/discussions)
76+
- **Documentation**: [docs.page/fluttercommunity/flutter_workmanager →](https://docs.page/fluttercommunity/flutter_workmanager)
7777

7878
## 🚀 Example App
7979

docs.json

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,39 @@
11
{
22
"name": "Flutter Workmanager",
3-
"description": "Background task execution for Flutter apps"
3+
"description": "Background task execution for Flutter apps",
4+
"sidebar": [
5+
{
6+
"text": "Get Started",
7+
"link": "/quickstart"
8+
},
9+
{
10+
"text": "Use Cases",
11+
"items": [
12+
{
13+
"text": "Sync Data from API",
14+
"link": "/usecases/data-sync"
15+
},
16+
{
17+
"text": "Upload Files",
18+
"link": "/usecases/upload-files"
19+
},
20+
{
21+
"text": "Periodic Cleanup",
22+
"link": "/usecases/periodic-cleanup"
23+
},
24+
{
25+
"text": "Fetch Notifications",
26+
"link": "/usecases/fetch-notifications"
27+
},
28+
{
29+
"text": "Database Maintenance",
30+
"link": "/usecases/database-maintenance"
31+
}
32+
]
33+
},
34+
{
35+
"text": "Debugging",
36+
"link": "/debugging"
37+
}
38+
]
439
}

docs/debugging.mdx

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
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.

docs/index.mdx

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,6 @@ description: Background task execution for Flutter apps
55

66
# Flutter Workmanager
77

8-
<p>
9-
<img src="https://img.shields.io/pub/v/workmanager.svg" alt="pub package"/>
10-
<img src="https://img.shields.io/github/actions/workflow/status/fluttercommunity/flutter_workmanager/test.yml?branch=main&label=tests" alt="tests"/>
11-
<img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="license"/>
12-
</p>
13-
148
Execute Dart code in the background, even when your app is closed. Perfect for data sync, file uploads, and periodic maintenance tasks.
159

1610
## Key Features
@@ -49,3 +43,13 @@ This plugin uses a **federated architecture**:
4943
- `workmanager_platform_interface` - Shared interface for platform implementations
5044

5145
All packages are automatically included when you add `workmanager` to pubspec.yaml.
46+
47+
## Get Started
48+
49+
Ready to add background tasks to your Flutter app?
50+
51+
**[→ Quick Start Guide](quickstart)** - Get up and running in minutes
52+
53+
## Example Project
54+
55+
See a complete working demo: **[Example App →](https://github.com/fluttercommunity/flutter_workmanager/tree/main/example)**

example/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,4 @@ The demo includes practical examples:
6060

6161
## Documentation
6262

63-
For detailed guides and real-world use cases, visit: **https://docs.workmanager.dev**
63+
For detailed guides and real-world use cases, visit: **[docs.page/fluttercommunity/flutter_workmanager →](https://docs.page/fluttercommunity/flutter_workmanager)**

0 commit comments

Comments
 (0)