-
Notifications
You must be signed in to change notification settings - Fork 356
Expand file tree
/
Copy pathmain.dart
More file actions
386 lines (366 loc) · 14.3 KB
/
main.dart
File metadata and controls
386 lines (366 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import 'dart:developer';
import 'dart:async';
import 'dart:io';
import 'dart:math' show Random;
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:workmanager/workmanager.dart';
void main() => runApp(MaterialApp(home: MyApp()));
const simpleTaskKey = "dev.fluttercommunity.workmanagerExample.simpleTask";
const rescheduledTaskKey =
"dev.fluttercommunity.workmanagerExample.rescheduledTask";
const failedTaskKey = "dev.fluttercommunity.workmanagerExample.failedTask";
const simpleDelayedTask =
"dev.fluttercommunity.workmanagerExample.simpleDelayedTask";
const simplePeriodicTask =
"dev.fluttercommunity.workmanagerExample.simplePeriodicTask";
const simplePeriodic1HourTask =
"dev.fluttercommunity.workmanagerExample.simplePeriodic1HourTask";
const iOSBackgroundAppRefresh =
"dev.fluttercommunity.workmanagerExample.iOSBackgroundAppRefresh";
const iOSBackgroundProcessingTask =
"dev.fluttercommunity.workmanagerExample.iOSBackgroundProcessingTask";
final List<String> allTasks = [
simpleTaskKey,
rescheduledTaskKey,
failedTaskKey,
simpleDelayedTask,
simplePeriodicTask,
simplePeriodic1HourTask,
iOSBackgroundAppRefresh,
iOSBackgroundProcessingTask,
];
// Pragma is mandatory if the App is obfuscated or using Flutter 3.1+
@pragma('vm:entry-point')
void callbackDispatcher() {
log('callbackDispatcher called');
Workmanager().executeTask((task, inputData) async {
log("callbackDispatcher called with task: $task");
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
print("$task started. inputData = $inputData");
await prefs.setString(task, 'Last ran at: ${DateTime.now().toString()}');
switch (task) {
case simpleTaskKey:
await prefs.setBool("test", true);
print("Bool from prefs: ${prefs.getBool("test")}");
break;
case rescheduledTaskKey:
final key = inputData!['key']!;
if (prefs.containsKey('unique-$key')) {
print('has been running before, task is successful');
return true;
} else {
await prefs.setBool('unique-$key', true);
print('reschedule task');
return false;
}
case failedTaskKey:
print('failed task');
return Future.error('failed');
case simpleDelayedTask:
print("$simpleDelayedTask was executed");
break;
case simplePeriodicTask:
print("$simplePeriodicTask was executed");
break;
case simplePeriodic1HourTask:
print("$simplePeriodic1HourTask was executed");
break;
case iOSBackgroundAppRefresh:
// To test, follow the instructions on https://developer.apple.com/documentation/backgroundtasks/starting_and_terminating_tasks_during_development
// and https://github.com/fluttercommunity/flutter_workmanager/blob/main/IOS_SETUP.md
Directory? tempDir = await getTemporaryDirectory();
String? tempPath = tempDir.path;
print(
"You can access other plugins in the background, for example Directory.getTemporaryDirectory(): $tempPath");
break;
case iOSBackgroundProcessingTask:
// To test, follow the instructions on https://developer.apple.com/documentation/backgroundtasks/starting_and_terminating_tasks_during_development
// and https://github.com/fluttercommunity/flutter_workmanager/blob/main/IOS_SETUP.md
// Processing tasks are started by iOS only when phone is idle, hence
// you need to manually trigger by following the docs and putting the App to background
await Future<void>.delayed(Duration(seconds: 40));
print("$task finished");
break;
default:
return Future.value(false);
}
// Return true to indicate that the task was successful
print("$task finished successfully");
return Future.value(true);
});
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool workmanagerInitialized = false;
String _prefsString = "empty";
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Flutter WorkManager Example"),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
"Plugin initialization",
style: Theme.of(context).textTheme.headlineSmall,
),
ElevatedButton(
child: Text("Start the Flutter background service"),
onPressed: () async {
if (Platform.isIOS) {
final status = await Permission.backgroundRefresh.status;
if (status != PermissionStatus.granted) {
_showNoPermission(context, status);
return;
}
}
if (!workmanagerInitialized) {
try {
await Workmanager().initialize(
callbackDispatcher,
isInDebugMode: true,
);
} catch (e) {
print('Error initializing Workmanager: $e');
return;
}
setState(() => workmanagerInitialized = true);
}
},
),
SizedBox(height: 8),
Text(
"Register task",
style: Theme.of(context).textTheme.headlineSmall,
),
// This task runs once.
// Most likely this will trigger immediately
ElevatedButton(
child: Text("Register OneOff Task"),
onPressed: () {
Workmanager().registerOneOffTask(
simpleTaskKey,
simpleTaskKey,
inputData: <String, dynamic>{
'int': 1,
'bool': true,
'double': 1.0,
'string': 'string',
'array': [1, 2, 3],
// 'map': {'key': 'value'},
},
);
},
),
ElevatedButton(
child: Text("Register rescheduled Task"),
onPressed: () {
Workmanager().registerOneOffTask(
rescheduledTaskKey,
rescheduledTaskKey,
inputData: <String, dynamic>{
'key': Random().nextInt(64000),
},
);
},
),
ElevatedButton(
child: Text("Register failed Task"),
onPressed: () {
Workmanager().registerOneOffTask(
failedTaskKey,
failedTaskKey,
);
},
),
//This task runs once
//This wait at least 10 seconds before running
ElevatedButton(
child: Text("Register Delayed OneOff Task"),
onPressed: () {
Workmanager().registerOneOffTask(
simpleDelayedTask,
simpleDelayedTask,
initialDelay: Duration(seconds: 10),
);
}),
SizedBox(height: 8),
Text(
"Register periodic task (android only)",
style: Theme.of(context).textTheme.headlineSmall,
),
//This task runs periodically
//It will wait at least 10 seconds before its first launch
//Since we have not provided a frequency it will be the default 15 minutes
ElevatedButton(
child: Text("Register Periodic Task (Android)"),
onPressed: Platform.isAndroid
? () {
Workmanager().registerPeriodicTask(
simplePeriodicTask,
simplePeriodicTask,
initialDelay: Duration(seconds: 10),
);
}
: null,
),
//This task runs periodically
//It will run about every hour
ElevatedButton(
child: Text("Register 1 hour Periodic Task (Android)"),
onPressed: Platform.isAndroid
? () {
Workmanager().registerPeriodicTask(
simplePeriodic1HourTask,
simplePeriodic1HourTask,
flexInterval: Duration(minutes: 15),
frequency: Duration(hours: 1),
);
}
: null),
// Currently we cannot provide frequency for iOS, hence it will be
// minimum 15 minutes after which iOS will reschedule
ElevatedButton(
child: Text('Register Periodic Background App Refresh (iOS)'),
onPressed: Platform.isIOS
? () async {
if (!workmanagerInitialized) {
_showNotInitialized();
return;
}
await Workmanager().registerPeriodicTask(
iOSBackgroundAppRefresh,
iOSBackgroundAppRefresh,
initialDelay: Duration(seconds: 10),
inputData: <String, dynamic>{}, //ignored on iOS
);
}
: null,
),
// This task runs only once, to perform a time consuming task at
// a later time decided by iOS.
// Processing tasks run only when the device is idle. iOS might
// terminate any running background processing tasks when the
// user starts using the device.
ElevatedButton(
child: Text('Register BackgroundProcessingTask (iOS)'),
onPressed: Platform.isIOS
? () async {
if (!workmanagerInitialized) {
_showNotInitialized();
return;
}
await Workmanager().registerProcessingTask(
iOSBackgroundProcessingTask,
iOSBackgroundProcessingTask,
initialDelay: Duration(seconds: 20),
);
}
: null,
),
SizedBox(height: 16),
ElevatedButton(
child: Text("isscheduled (Android)"),
onPressed: Platform.isAndroid
? () async {
final workInfo =
await Workmanager().isScheduledByUniqueName(
simplePeriodicTask,
);
print('isscheduled = $workInfo');
}
: null),
SizedBox(height: 8),
Text(
"Task cancellation",
style: Theme.of(context).textTheme.headlineSmall,
),
ElevatedButton(
child: Text("Cancel All"),
onPressed: () async {
await Workmanager().cancelAll();
print('Cancel all tasks completed');
},
),
SizedBox(height: 15),
ElevatedButton(
child: Text('Refresh stats'),
onPressed: _refreshStats,
),
SizedBox(height: 10),
SingleChildScrollView(
child: Text(
'Task run stats:\n'
'${workmanagerInitialized ? '' : 'Workmanager not initialized'}'
'\n$_prefsString',
),
),
],
),
),
),
),
);
}
// Refresh/get saved prefs
void _refreshStats() async {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
_prefsString = '';
for (final task in allTasks) {
_prefsString = '$_prefsString \n$task:\n${prefs.getString(task)}\n';
}
if (Platform.isIOS) {
Workmanager().printScheduledTasks();
}
setState(() {});
}
void _showNotInitialized() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Workmanager not initialized'),
content: Text('Workmanager is not initialized, please initialize'),
actions: <Widget>[
TextButton(
child: Text('OK'),
onPressed: () => Navigator.of(context).pop(),
),
],
);
},
);
}
void _showNoPermission(BuildContext context, PermissionStatus hasPermission) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('No permission'),
content: Text('Background app refresh is disabled, please enable in '
'App settings. Status ${hasPermission.name}'),
actions: <Widget>[
TextButton(
child: Text('OK'),
onPressed: () => Navigator.of(context).pop(),
),
],
);
},
);
}
}