|
1 | 1 | // Copyright 2017 The Chromium Authors. All rights reserved. |
2 | 2 | // Use of this source code is governed by a BSD-style license that can be |
3 | 3 | // found in the LICENSE file. |
| 4 | + |
4 | 5 | import 'dart:developer' as developer; |
5 | 6 | import 'dart:isolate'; |
6 | 7 | import 'dart:math'; |
7 | | -import 'dart:ui'; |
8 | 8 |
|
9 | 9 | import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart'; |
10 | 10 | import 'package:permission_handler/permission_handler.dart'; |
11 | 11 | import 'package:shared_preferences/shared_preferences.dart'; |
12 | 12 | import 'package:flutter/material.dart'; |
13 | 13 |
|
14 | | -/// The [SharedPreferences] key to access the alarm fire count. |
15 | 14 | const String countKey = 'count'; |
16 | | - |
17 | | -/// The name associated with the UI isolate's [SendPort]. |
18 | 15 | const String isolateName = 'isolate'; |
19 | 16 |
|
20 | | -/// A port used to communicate from a background isolate to the UI isolate. |
21 | | -ReceivePort port = ReceivePort(); |
22 | | - |
23 | | -/// Global [SharedPreferences] object. |
24 | | -SharedPreferences? prefs; |
| 17 | +final ReceivePort port = ReceivePort(); |
| 18 | +late final SharedPreferences prefs; |
25 | 19 |
|
| 20 | +/// Entry point of the app |
26 | 21 | Future<void> main() async { |
27 | 22 | WidgetsFlutterBinding.ensureInitialized(); |
28 | 23 |
|
29 | | - // Register the UI isolate's SendPort to allow for communication from the |
30 | | - // background isolate. |
31 | | - IsolateNameServer.registerPortWithName( |
32 | | - port.sendPort, |
33 | | - isolateName, |
34 | | - ); |
| 24 | + IsolateNameServer.registerPortWithName(port.sendPort, isolateName); |
35 | 25 | prefs = await SharedPreferences.getInstance(); |
36 | | - if (!prefs!.containsKey(countKey)) { |
37 | | - await prefs!.setInt(countKey, 0); |
| 26 | + if (!prefs.containsKey(countKey)) { |
| 27 | + await prefs.setInt(countKey, 0); |
38 | 28 | } |
39 | 29 |
|
40 | 30 | runApp(const AlarmManagerExampleApp()); |
41 | 31 | } |
42 | 32 |
|
43 | | -/// Example app for Espresso plugin. |
44 | 33 | class AlarmManagerExampleApp extends StatelessWidget { |
45 | 34 | const AlarmManagerExampleApp({super.key}); |
46 | 35 |
|
47 | | - // This widget is the root of your application. |
48 | 36 | @override |
49 | 37 | Widget build(BuildContext context) { |
50 | 38 | return MaterialApp( |
51 | | - title: 'Flutter Demo', |
| 39 | + title: 'Flutter Alarm Manager', |
52 | 40 | theme: ThemeData( |
53 | 41 | useMaterial3: true, |
54 | 42 | colorSchemeSeed: const Color(0x9f4376f8), |
55 | 43 | ), |
56 | | - home: const _AlarmHomePage(), |
| 44 | + home: const AlarmHomePage(), |
57 | 45 | ); |
58 | 46 | } |
59 | 47 | } |
60 | 48 |
|
61 | | -class _AlarmHomePage extends StatefulWidget { |
62 | | - const _AlarmHomePage(); |
| 49 | +class AlarmHomePage extends StatefulWidget { |
| 50 | + const AlarmHomePage({super.key}); |
63 | 51 |
|
64 | 52 | @override |
65 | 53 | _AlarmHomePageState createState() => _AlarmHomePageState(); |
66 | 54 | } |
67 | 55 |
|
68 | | -class _AlarmHomePageState extends State<_AlarmHomePage> { |
| 56 | +class _AlarmHomePageState extends State<AlarmHomePage> { |
69 | 57 | int _counter = 0; |
70 | 58 | PermissionStatus _exactAlarmPermissionStatus = PermissionStatus.granted; |
| 59 | + static SendPort? uiSendPort; |
71 | 60 |
|
72 | 61 | @override |
73 | 62 | void initState() { |
74 | 63 | super.initState(); |
75 | 64 | AndroidAlarmManager.initialize(); |
76 | 65 | _checkExactAlarmPermission(); |
77 | | - |
78 | | - // Register for events from the background isolate. These messages will |
79 | | - // always coincide with an alarm firing. |
80 | | - port.listen((_) async => await _incrementCounter()); |
| 66 | + port.listen((_) => _incrementCounter()); |
81 | 67 | } |
82 | 68 |
|
83 | | - void _checkExactAlarmPermission() async { |
84 | | - final currentStatus = await Permission.scheduleExactAlarm.status; |
| 69 | + Future<void> _checkExactAlarmPermission() async { |
| 70 | + final status = await Permission.scheduleExactAlarm.status; |
85 | 71 | if (!mounted) return; |
86 | | - setState(() { |
87 | | - _exactAlarmPermissionStatus = currentStatus; |
88 | | - }); |
| 72 | + setState(() => _exactAlarmPermissionStatus = status); |
89 | 73 | } |
90 | 74 |
|
91 | 75 | Future<void> _incrementCounter() async { |
92 | | - developer.log('Increment counter!'); |
93 | | - // Ensure we've loaded the updated count from the background isolate. |
94 | | - await prefs?.reload(); |
95 | | - |
96 | | - setState(() { |
97 | | - _counter++; |
98 | | - }); |
| 76 | + developer.log('Increment counter!', name: 'AlarmManagerExample'); |
| 77 | + await prefs.reload(); |
| 78 | + if (!mounted) return; |
| 79 | + setState(() => _counter++); |
99 | 80 | } |
100 | 81 |
|
101 | | - // The background |
102 | | - static SendPort? uiSendPort; |
103 | | - |
104 | | - // The callback for our alarm |
105 | 82 | @pragma('vm:entry-point') |
106 | 83 | static Future<void> callback() async { |
107 | | - developer.log('Alarm fired!'); |
108 | | - // Get the previous cached count and increment it. |
109 | 84 | final prefs = await SharedPreferences.getInstance(); |
110 | 85 | final currentCount = prefs.getInt(countKey) ?? 0; |
111 | 86 | await prefs.setInt(countKey, currentCount + 1); |
112 | 87 |
|
113 | | - // This will be null if we're running in the background. |
114 | 88 | uiSendPort ??= IsolateNameServer.lookupPortByName(isolateName); |
115 | 89 | uiSendPort?.send(null); |
116 | 90 | } |
117 | 91 |
|
| 92 | + Future<void> _requestPermission() async { |
| 93 | + await Permission.scheduleExactAlarm |
| 94 | + .onGrantedCallback(() => setState(() => _exactAlarmPermissionStatus = PermissionStatus.granted)) |
| 95 | + .request(); |
| 96 | + } |
| 97 | + |
| 98 | + Future<void> _scheduleAlarm() async { |
| 99 | + await AndroidAlarmManager.oneShot( |
| 100 | + const Duration(seconds: 5), |
| 101 | + Random().nextInt(1 << 31), |
| 102 | + callback, |
| 103 | + exact: true, |
| 104 | + wakeup: true, |
| 105 | + ); |
| 106 | + } |
| 107 | + |
118 | 108 | @override |
119 | 109 | Widget build(BuildContext context) { |
120 | 110 | final textStyle = Theme.of(context).textTheme.headlineMedium; |
121 | 111 | return Scaffold( |
122 | | - appBar: AppBar( |
123 | | - title: const Text('Android alarm manager plus example'), |
124 | | - elevation: 4, |
125 | | - ), |
| 112 | + appBar: AppBar(title: const Text('Android Alarm Manager Example')), |
126 | 113 | body: Center( |
127 | 114 | child: Column( |
128 | | - crossAxisAlignment: CrossAxisAlignment.center, |
129 | 115 | mainAxisAlignment: MainAxisAlignment.center, |
130 | 116 | children: [ |
131 | 117 | const Spacer(), |
132 | | - Text( |
133 | | - 'Alarms fired during this run of the app: $_counter', |
134 | | - style: textStyle, |
135 | | - textAlign: TextAlign.center, |
136 | | - ), |
| 118 | + Text('Alarms fired during this run: $_counter', style: textStyle, textAlign: TextAlign.center), |
137 | 119 | const SizedBox(height: 16), |
| 120 | + Text('Total alarms fired: ${prefs.getInt(countKey)}', style: textStyle, textAlign: TextAlign.center), |
| 121 | + const Spacer(), |
138 | 122 | Text( |
139 | | - 'Total alarms fired since app installation: ${prefs?.getInt(countKey).toString() ?? ''}', |
140 | | - style: textStyle, |
| 123 | + _exactAlarmPermissionStatus.isDenied |
| 124 | + ? 'Exact alarm permission denied. Alarms not available.' |
| 125 | + : 'Exact alarm permission granted. Alarms available.', |
141 | 126 | textAlign: TextAlign.center, |
142 | 127 | ), |
143 | | - const Spacer(), |
144 | | - if (_exactAlarmPermissionStatus.isDenied) |
145 | | - Text( |
146 | | - 'SCHEDULE_EXACT_ALARM is denied\n\nAlarms scheduling is not available', |
147 | | - textAlign: TextAlign.center, |
148 | | - style: Theme.of(context).textTheme.titleMedium, |
149 | | - ) |
150 | | - else |
151 | | - Text( |
152 | | - 'SCHEDULE_EXACT_ALARM is granted\n\nAlarms scheduling is available', |
153 | | - textAlign: TextAlign.center, |
154 | | - style: Theme.of(context).textTheme.titleMedium, |
155 | | - ), |
156 | 128 | const SizedBox(height: 32), |
157 | 129 | ElevatedButton( |
158 | | - onPressed: _exactAlarmPermissionStatus.isDenied |
159 | | - ? () async { |
160 | | - await Permission.scheduleExactAlarm |
161 | | - .onGrantedCallback(() => setState(() { |
162 | | - _exactAlarmPermissionStatus = |
163 | | - PermissionStatus.granted; |
164 | | - })) |
165 | | - .request(); |
166 | | - } |
167 | | - : null, |
| 130 | + onPressed: _exactAlarmPermissionStatus.isDenied ? _requestPermission : null, |
168 | 131 | child: const Text('Request exact alarm permission'), |
169 | 132 | ), |
170 | 133 | const SizedBox(height: 32), |
171 | 134 | ElevatedButton( |
172 | | - onPressed: _exactAlarmPermissionStatus.isGranted |
173 | | - ? () async { |
174 | | - await AndroidAlarmManager.oneShot( |
175 | | - const Duration(seconds: 5), |
176 | | - // Ensure we have a unique alarm ID. |
177 | | - Random().nextInt(pow(2, 31) as int), |
178 | | - callback, |
179 | | - exact: true, |
180 | | - wakeup: true, |
181 | | - ); |
182 | | - } |
183 | | - : null, |
| 135 | + onPressed: _exactAlarmPermissionStatus.isGranted ? _scheduleAlarm : null, |
184 | 136 | child: const Text('Schedule OneShot Alarm'), |
185 | 137 | ), |
186 | 138 | const Spacer(), |
|
0 commit comments