feat: compose Android app and verify native calendar and reminders
This commit is contained in:
@@ -170,40 +170,43 @@ class AppController extends ChangeNotifier {
|
||||
}
|
||||
calendarSyncError = null;
|
||||
});
|
||||
Future<void> enableCalendarFromUserAction(String calendarId) =>
|
||||
_run(() async {
|
||||
if (isDemo) throw StateError('示例课表不会导入日历');
|
||||
if (snapshot.settings.semester == null) throw StateError('请先设置学期');
|
||||
if (!await calendar.requestAccess()) {
|
||||
calendarSyncError = '日历权限未获允许';
|
||||
return;
|
||||
}
|
||||
if (snapshot.calendarCleanupPending) {
|
||||
await _cleanupCalendar();
|
||||
}
|
||||
final calendars = await calendar.listWritableCalendars();
|
||||
if (!calendars.any((c) => c.id == calendarId)) {
|
||||
calendarSyncError = '请选择可写入的日历';
|
||||
return;
|
||||
}
|
||||
final settings = snapshot.settings.copyWith(
|
||||
calendarEnabled: true,
|
||||
calendarId: calendarId,
|
||||
);
|
||||
try {
|
||||
final ids = await calendar.sync(
|
||||
ScheduleEngine.occurrences(snapshot.courses, settings.semester!),
|
||||
calendarId,
|
||||
snapshot.calendarEventIds,
|
||||
);
|
||||
await _save(
|
||||
snapshot.copyWith(settings: settings, calendarEventIds: ids),
|
||||
);
|
||||
calendarSyncError = null;
|
||||
} catch (_) {
|
||||
calendarSyncError = '日历同步失败,可重试';
|
||||
}
|
||||
});
|
||||
Future<void> enableCalendarFromUserAction(
|
||||
String calendarId,
|
||||
) => _run(() async {
|
||||
if (isDemo) throw StateError('示例课表不会导入日历');
|
||||
if (snapshot.settings.semester == null) throw StateError('请先设置学期');
|
||||
if (!await calendar.requestAccess()) {
|
||||
calendarSyncError = '日历权限未获允许';
|
||||
return;
|
||||
}
|
||||
if (snapshot.calendarCleanupPending) {
|
||||
await _cleanupCalendar();
|
||||
}
|
||||
final calendars = await calendar.listWritableCalendars();
|
||||
if (!calendars.any((c) => c.id == calendarId)) {
|
||||
calendarSyncError = '请选择可写入的日历';
|
||||
return;
|
||||
}
|
||||
final settings = snapshot.settings.copyWith(
|
||||
calendarEnabled: true,
|
||||
calendarId: calendarId,
|
||||
);
|
||||
// Keep the chosen calendar for recovery if the first native sync fails midway.
|
||||
await _save(
|
||||
snapshot.copyWith(settings: settings.copyWith(calendarEnabled: false)),
|
||||
);
|
||||
try {
|
||||
final ids = await calendar.sync(
|
||||
ScheduleEngine.occurrences(snapshot.courses, settings.semester!),
|
||||
calendarId,
|
||||
snapshot.calendarEventIds,
|
||||
);
|
||||
await _save(snapshot.copyWith(settings: settings, calendarEventIds: ids));
|
||||
calendarSyncError = null;
|
||||
} catch (_) {
|
||||
calendarSyncError = '日历同步失败,可重试';
|
||||
}
|
||||
});
|
||||
Future<void> enableRemindersFromUserAction() => _run(() async {
|
||||
if (isDemo) throw StateError('示例课表不会生成提醒');
|
||||
await notifications.requestPermissions();
|
||||
@@ -225,6 +228,10 @@ class AppController extends ChangeNotifier {
|
||||
Future<void> _cleanupCalendar() async {
|
||||
try {
|
||||
await calendar.deleteOwned(snapshot.calendarEventIds);
|
||||
final calendarId = snapshot.settings.calendarId;
|
||||
if (calendarId != null) {
|
||||
await calendar.deleteOwned(await calendar.ownedEventIds(calendarId));
|
||||
}
|
||||
await _save(
|
||||
snapshot.copyWith(calendarEventIds: {}, calendarCleanupPending: false),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
|
||||
import '../domain/schedule_engine.dart';
|
||||
import '../features/timetable/course_details.dart';
|
||||
|
||||
import 'app_controller.dart';
|
||||
import 'app_theme.dart';
|
||||
@@ -13,28 +17,40 @@ class HepanApp extends StatelessWidget {
|
||||
required this.controller,
|
||||
this.schoolBuilder,
|
||||
this.school,
|
||||
this.notificationSelection,
|
||||
});
|
||||
final AppController controller;
|
||||
final Widget Function()? schoolBuilder;
|
||||
final SchoolSession? school;
|
||||
final ValueNotifier<String?>? notificationSelection;
|
||||
@override
|
||||
Widget build(BuildContext context) => MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
title: '河畔Everyday',
|
||||
theme: hepanTheme(),
|
||||
locale: const Locale('zh', 'CN'),
|
||||
supportedLocales: const [Locale('zh', 'CN')],
|
||||
localizationsDelegates: GlobalMaterialLocalizations.delegates,
|
||||
home: _Shell(
|
||||
controller: controller,
|
||||
schoolBuilder: schoolBuilder,
|
||||
school: school,
|
||||
notificationSelection: notificationSelection,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _Shell extends StatefulWidget {
|
||||
const _Shell({required this.controller, this.schoolBuilder, this.school});
|
||||
const _Shell({
|
||||
required this.controller,
|
||||
this.schoolBuilder,
|
||||
this.school,
|
||||
this.notificationSelection,
|
||||
});
|
||||
final AppController controller;
|
||||
final Widget Function()? schoolBuilder;
|
||||
final SchoolSession? school;
|
||||
final ValueNotifier<String?>? notificationSelection;
|
||||
@override
|
||||
State<_Shell> createState() => _ShellState();
|
||||
}
|
||||
@@ -45,14 +61,45 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
widget.notificationSelection?.addListener(_selectNotification);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _selectNotification());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
widget.notificationSelection?.removeListener(_selectNotification);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _selectNotification() async {
|
||||
final key = widget.notificationSelection?.value;
|
||||
if (key == null || !mounted) {
|
||||
return;
|
||||
}
|
||||
widget.notificationSelection!.value = null;
|
||||
await widget.controller.leaveDemo();
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).popUntil((route) => route.isFirst);
|
||||
setState(() => _tab = 0);
|
||||
final semester = widget.controller.snapshot.settings.semester;
|
||||
if (semester == null) {
|
||||
return;
|
||||
}
|
||||
final events = ScheduleEngine.occurrences(
|
||||
widget.controller.snapshot.courses,
|
||||
semester,
|
||||
).where((e) => e.key == key);
|
||||
if (events.isNotEmpty) {
|
||||
showCourseDetails(context, events.first);
|
||||
} else {
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(const SnackBar(content: Text('这门课程已更新,请查看当前课表')));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
|
||||
@@ -34,6 +34,16 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
}
|
||||
|
||||
Future<void> _calendar(bool enabled) async {
|
||||
try {
|
||||
await _calendarAction(enabled);
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
_notice('日历暂时不可用,请检查权限后重试');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _calendarAction(bool enabled) async {
|
||||
final c = widget.controller;
|
||||
if (enabled) {
|
||||
if (!await c.calendar.requestAccess()) {
|
||||
|
||||
+41
-119
@@ -1,122 +1,44 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:timezone/data/latest.dart' as tzdata;
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
// This widget is the root of your application.
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: 'Flutter Demo',
|
||||
theme: ThemeData(
|
||||
// This is the theme of your application.
|
||||
//
|
||||
// TRY THIS: Try running your application with "flutter run". You'll see
|
||||
// the application has a purple toolbar. Then, without quitting the app,
|
||||
// try changing the seedColor in the colorScheme below to Colors.green
|
||||
// and then invoke "hot reload" (save your changes or press the "hot
|
||||
// reload" button in a Flutter-supported IDE, or press "r" if you used
|
||||
// the command line to start the app).
|
||||
//
|
||||
// Notice that the counter didn't reset back to zero; the application
|
||||
// state is not lost during the reload. To reset the state, use hot
|
||||
// restart instead.
|
||||
//
|
||||
// This works for code too, not just values: Most code changes can be
|
||||
// tested with just a hot reload.
|
||||
colorScheme: .fromSeed(seedColor: Colors.deepPurple),
|
||||
),
|
||||
home: const MyHomePage(title: 'Flutter Demo Home Page'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MyHomePage extends StatefulWidget {
|
||||
const MyHomePage({super.key, required this.title});
|
||||
|
||||
// This widget is the home page of your application. It is stateful, meaning
|
||||
// that it has a State object (defined below) that contains fields that affect
|
||||
// how it looks.
|
||||
|
||||
// This class is the configuration for the state. It holds the values (in this
|
||||
// case the title) provided by the parent (in this case the App widget) and
|
||||
// used by the build method of the State. Fields in a Widget subclass are
|
||||
// always marked "final".
|
||||
|
||||
final String title;
|
||||
|
||||
@override
|
||||
State<MyHomePage> createState() => _MyHomePageState();
|
||||
}
|
||||
|
||||
class _MyHomePageState extends State<MyHomePage> {
|
||||
int _counter = 0;
|
||||
|
||||
void _incrementCounter() {
|
||||
setState(() {
|
||||
// This call to setState tells the Flutter framework that something has
|
||||
// changed in this State, which causes it to rerun the build method below
|
||||
// so that the display can reflect the updated values. If we changed
|
||||
// _counter without calling setState(), then the build method would not be
|
||||
// called again, and so nothing would appear to happen.
|
||||
_counter++;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// This method is rerun every time setState is called, for instance as done
|
||||
// by the _incrementCounter method above.
|
||||
//
|
||||
// The Flutter framework has been optimized to make rerunning build methods
|
||||
// fast, so that you can just rebuild anything that needs updating rather
|
||||
// than having to individually change instances of widgets.
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
// TRY THIS: Try changing the color here to a specific color (to
|
||||
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
|
||||
// change color while the other colors stay the same.
|
||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||
// Here we take the value from the MyHomePage object that was created by
|
||||
// the App.build method, and use it to set our appbar title.
|
||||
title: Text(widget.title),
|
||||
),
|
||||
body: Center(
|
||||
// Center is a layout widget. It takes a single child and positions it
|
||||
// in the middle of the parent.
|
||||
child: Column(
|
||||
// Column is also a layout widget. It takes a list of children and
|
||||
// arranges them vertically. By default, it sizes itself to fit its
|
||||
// children horizontally, and tries to be as tall as its parent.
|
||||
//
|
||||
// Column has various properties to control how it sizes itself and
|
||||
// how it positions its children. Here we use mainAxisAlignment to
|
||||
// center the children vertically; the main axis here is the vertical
|
||||
// axis because Columns are vertical (the cross axis would be
|
||||
// horizontal).
|
||||
//
|
||||
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
|
||||
// action in the IDE, or press "p" in the console), to see the
|
||||
// wireframe for each widget.
|
||||
mainAxisAlignment: .center,
|
||||
children: [
|
||||
const Text('You have pushed the button this many times:'),
|
||||
Text(
|
||||
'$_counter',
|
||||
style: Theme.of(context).textTheme.headlineMedium,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: _incrementCounter,
|
||||
tooltip: 'Increment',
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
);
|
||||
}
|
||||
import 'app/app_controller.dart';
|
||||
import 'app/hepan_app.dart';
|
||||
import 'data/file_snapshot_store.dart';
|
||||
import 'services/local_notification_service.dart';
|
||||
import 'services/android_calendar_service.dart';
|
||||
import 'features/school/school_session.dart';
|
||||
import 'features/school/school_auth_page.dart';
|
||||
|
||||
Widget buildApplication(
|
||||
AppController controller, {
|
||||
ValueNotifier<String?>? notificationSelection,
|
||||
SchoolSession? school,
|
||||
}) => HepanApp(
|
||||
controller: controller,
|
||||
notificationSelection: notificationSelection,
|
||||
school: school,
|
||||
schoolBuilder: school == null
|
||||
? null
|
||||
: () => SchoolAuthPage(session: school, controller: controller),
|
||||
);
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
tzdata.initializeTimeZones();
|
||||
final selection = ValueNotifier<String?>(null);
|
||||
final gateway = PluginReminderGateway(onTap: (key) => selection.value = key);
|
||||
final controller = AppController(
|
||||
FileSnapshotStore(await getApplicationSupportDirectory()),
|
||||
LocalNotificationService(gateway),
|
||||
AndroidCalendarService(MethodCalendarGateway()),
|
||||
DateTime.now,
|
||||
);
|
||||
await controller.initialize();
|
||||
runApp(
|
||||
buildApplication(
|
||||
controller,
|
||||
notificationSelection: selection,
|
||||
school: SchoolSession(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -51,6 +51,11 @@ class AndroidCalendarService extends CalendarService {
|
||||
AndroidCalendarService(this.gateway);
|
||||
final CalendarGateway gateway;
|
||||
@override
|
||||
Future<Map<String, String>> ownedEventIds(String calendarId) async => {
|
||||
for (final event in await gateway.ownedEvents(calendarId))
|
||||
if (event.owned && event.calendarId == calendarId) event.key: event.id,
|
||||
};
|
||||
@override
|
||||
Future<bool> requestAccess() => gateway.requestAccess();
|
||||
@override
|
||||
Future<List<DeviceCalendar>> listWritableCalendars() => gateway.calendars();
|
||||
|
||||
@@ -14,4 +14,6 @@ abstract class CalendarService {
|
||||
Map<String, String> knownEventIds,
|
||||
);
|
||||
Future<void> deleteOwned(Map<String, String> eventIds);
|
||||
Future<Map<String, String>> ownedEventIds(String calendarId) async =>
|
||||
const {};
|
||||
}
|
||||
|
||||
@@ -147,18 +147,27 @@ class PluginReminderGateway extends ReminderGateway {
|
||||
final void Function(String key)? onTap;
|
||||
final _plugin = FlutterLocalNotificationsPlugin();
|
||||
Future<void>? _initializing;
|
||||
Future<void> initialize() => _initializing ??= () async {
|
||||
await _plugin.initialize(
|
||||
settings: const InitializationSettings(
|
||||
android: AndroidInitializationSettings('ic_stat_calendar'),
|
||||
),
|
||||
onDidReceiveNotificationResponse: (response) => _select(response.payload),
|
||||
);
|
||||
final launch = await _plugin.getNotificationAppLaunchDetails();
|
||||
if (launch?.didNotificationLaunchApp == true) {
|
||||
_select(launch?.notificationResponse?.payload);
|
||||
Future<void> initialize() => _initializing ??= Future<void>(() async {
|
||||
try {
|
||||
final ready = await _plugin.initialize(
|
||||
settings: const InitializationSettings(
|
||||
android: AndroidInitializationSettings('ic_stat_calendar'),
|
||||
),
|
||||
onDidReceiveNotificationResponse: (response) =>
|
||||
_select(response.payload),
|
||||
);
|
||||
if (ready != true) {
|
||||
throw StateError('通知服务初始化失败');
|
||||
}
|
||||
final launch = await _plugin.getNotificationAppLaunchDetails();
|
||||
if (launch?.didNotificationLaunchApp == true) {
|
||||
_select(launch?.notificationResponse?.payload);
|
||||
}
|
||||
} catch (_) {
|
||||
_initializing = null;
|
||||
rethrow;
|
||||
}
|
||||
}();
|
||||
});
|
||||
void _select(String? payload) {
|
||||
if (payload?.startsWith('hepan:') == true) {
|
||||
onTap?.call(payload!.substring(6));
|
||||
|
||||
Reference in New Issue
Block a user