feat: compose Android app and verify native calendar and reminders

This commit is contained in:
Codex
2026-10-13 09:14:47 +08:00
parent 2c4256b880
commit 5ceab20b67
37 changed files with 695 additions and 229 deletions
+3
View File
@@ -8,3 +8,6 @@ android/local.properties
*.log
.superpowers/
dist/
artifacts/*.xml
artifacts/emulator-*.txt
artifacts/screenshots/probe-state*.png
+37 -28
View File
@@ -1,47 +1,56 @@
# 河畔 Everyday
# 河畔Everyday
电子科技大学研究生课表 APP。采用 Flutter,优先 Android,后续支持 iOS。
电子科技大学研究生课表 APP,Flutter 实现,Android 首版 0.1.0+1,Android 7.0 及以上。iOS 尚未配置。
当前阶段:Android 开发环境已配置,首版设计文件已确认,实现计划待审核;尚未生成业务代码或 APP 安装包。
已实现:周一至周日、11 节学校作息、跨节课程条形卡片、课程详情与冲突提示、两个无文字图标的玻璃悬浮 Dock、单色/多彩设置、学期开始日/周数设置、JSON 预览导入、本地保存/备份恢复、课前通知及手机日历同步。
## 开发环境
学校认证提供自绘登录入口与官方 WebView。**本人登录、验证码及研究生课表自动识别仍待真实页面联调**,目前不会假装成功导入。详见 [学校接入状态](docs/school-integration-status.md)。
项目工具与缓存放在 `.tools/`,不会进入版本控制。使用官方发行版及 SHA-256 校验:
## 体验
- Flutter 3.47.7 稳定版,Dart 3.13.5。
- Microsoft OpenJDK 17.0.20.1。
- Android 命令行工具 22.0、Android API 36、Build Tools 36.0.0、Platform Tools。
- Flutter 配套 NDK 28.2.13676358、CMake 3.22.1。
- 可选 Android Emulator 与 Android 16(API 36)Google APIs x86_64 镜像。
安装 `dist/hepan-everyday-debug.apk`。这是开发测试包,不是商店发布包。首次打开点“体验示例课表”即可预览;示例课程不会写入手机日历或触发通知。
在 Windows PowerShell 中,进入本目录后,安装与检查环境:
自己的课程:在“我的 → 课表设置”填写学校实际开始日和周数,再通过“导入课表文件”导入 JSON 并确认预览。默认提前 15 分钟提醒,可选 5、10、15、30、60 分钟或关闭。首次启用需要允许通知;没有精确闹钟权限时会显示可能延迟。
```powershell
./scripts/setup-android.ps1 -WithEmulator
```
日历同步需授权并选择可写日历。关闭可保留或删除本 APP 创建的日程。删除时检查课程实例与本 APP 专属标记,不操作其他日程;清理失败保留映射并可重试。日历事件不创建第二份系统提醒。
安装时需要访问官方下载源和软件包服务,并接受 Android SDK 开发工具许可。安装日志与许可文本保留在 `.tools/`。安装脚本只在项目内放置工具;Flutter 自身会保存 SDK 路径配置。
## JSON 文件
每次打开新的 PowerShell 终端后激活环境:
样例:[schedule.schema-v1.json](examples/schedule.schema-v1.json)。
| 字段 | 含义 |
|---|---|
| schemaVersion | 固定为 1 |
| isDemo | 样例为 true;导入本人课程改成 false |
| explicitlyEmpty | 只有明确要清空且 courses=[] 时设 true,并在预览再次确认 |
| id | 每条课程安排唯一的非空标识 |
| name / teacher / room | 课程名、教师、教室,均非空 |
| weekday | 周一至周日:1–7 |
| startPeriod / endPeriod | 开始/结束节次:1–11,包含边界 |
| weeks | 实际上课周次数组:1–30;单双周展开成明确周次 |
同一课程不同星期或不同节次,应使用不同 id。文件上限 2 MB。导入文件不能冒充学校来源;示例模式不覆盖真实课表。
## 开发与构建
源码位于 `mobile/`。本次工具在 `C:/Users/david/Desktop/app/.tools`,不会进入 Git。Windows PowerShell:
```powershell
$env:HEPAN_TOOLCHAIN_ROOT='C:/Users/david/Desktop/app/.tools'
. ./scripts/android-env.ps1
flutter doctor -v
flutter devices
Set-Location mobile
flutter pub get
flutter analyze
flutter test
flutter run -d emulator-5554
```
真机调试:在 Android 手机打开开发者选项和 USB 调试,通过 USB 连接电脑,在手机上允许电脑调试,然后检查 `flutter devices`。如果 Windows 无法识别手机,根据手机厂商说明安装官方 USB 驱动。不要在聊天中提供学校账号密码。
模拟器需 Windows 支持的硬件虚拟化环境;环境检查与设备启动结果记录在 `docs/android-setup-status.md`。安装完成后可使用:
回到仓库根目录构建:
```powershell
. ./scripts/android-env.ps1
./scripts/create-android-emulator.ps1
emulator -avd hepan_everyday
./scripts/build-android.ps1
```
已创建的虚拟设备会重复使用,不覆盖其数据。
构建成功才复制新 APK 到 `dist/`。工具版本与设备环境见 [Android 环境](docs/android-setup-status.md)。其他电脑可使用 `scripts/setup-android.ps1 -WithEmulator` 安装环境,并将构建脚本 ToolchainRoot 指向对应 `.tools` 目录。
## 首版设计
见 [已确认的首版设计](docs/superpowers/specs/2026-10-12-hepan-everyday-design.md)与[实现计划](docs/superpowers/plans/2026-10-12-hepan-everyday-android.md)。学校真实课表解析需要在用户本人认证后的页面上验证。
设备集成检查见 [验证记录](docs/android-mvp-validation.md)。系统日历测试仅运行于专用模拟器的 `Hepan_Integration_Test` 测试日历,需提前允许测试 APP 读取和写入日历。`mobile/tool/reminder_probe.dart` 是短时系统提醒测试入口,交付 APK 始终使用 `lib/main.dart`。
Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 223 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

+32
View File
@@ -0,0 +1,32 @@
# Android 首版验证记录
日期:2026-10-13。测试环境:Flutter 3.47.7 / Dart 3.13.5 / JDK 17;Android 16 API 36,Pixel 7 模拟器,1080×2400。首版版本 0.1.0+1,包 ID com.example.hepan_everyday,最低 Android 7.0(API 24)。
## 已验证
- `flutter analyze`:No issues found。
- `flutter test`:51 项通过,包括 11 节时间、上海时区和非周一开始日、不连续周次、导入拒绝保留原课表、存储损坏恢复、示例隔离、通知去重和权限降级、日历中断恢复与归属检查、200% 字体和重叠课程、通知点击详情。
- `integration_test/app_flow_test.dart` 在 Android 模拟器通过:两页导航、单色设置、实际日期选择器和学期周数保存、导入预览取消与确认、示例不改真实保存文件、错误导入保持数据、重开恢复。
- `integration_test/calendar_bridge_test.dart` 在专用 Hepan_Integration_Test 日历通过:创建、再次同步更新同一 ID、映射丢失后找回、错误 key 无法删除、删除自有事件。设备实际查询表明 Unrelated_fixture 事件保留,CalendarContract.Reminders 无记录。
- 首次真实 APK 构建、安装、启动成功。初次编译下载依赖用时约 695 秒,后续构建约 40 秒。
- 短时通知使用独立测试入口 tool/reminder_probe.dart,不写入用户课表文件。应用退到后台后系统收到通知,实际标题及内容包含测试课程、教师和教室;点击通知打开对应课程详情。
## 补充设备结果
- 模拟器重启后:未重新打开 APP,系统仍送出已安排的测试通知;启动正式 APP 后,空课表协调取消残留自有通知。
- 已重建并安装 lib/main.dart 正式入口 APK,核实包名、0.1.0+1、API 24/36 和三种 Android 架构。示例课表、我的、周日、末节、设置和 200% 字体已有设备截图;验证 APK 不包含测试入口。
- 独立代码审查进行中,结论另记。
## 仍需本人手机验证
- 本人学校登录、验证码、二次验证、真实研究生课表解析。目前解析器明确提示待联调,保护已有课表;见 school-integration-status.md。
- 真实手机的厂商省电、锁屏通知、长时间后台与真机重启行为;模拟器结果不能代替真机。
- 不同手机日历应用与云账户对自定义归属标记的同步行为。
- iOS 尚未配置及验证。
## 本轮修复和设备异常
日历设备测试复现 Calendar Provider 不允许“事件单条 URI + selection”操作;改为集合 URI 加事件 ID、应用包和实例标记条件,原设备测试随后通过。首次设备界面测试时模拟器连接中断;重新启动并使用软件图形模式后同项测试通过。首次权限检查未通过来自测试框架重装应用;本轮单独授权后完成系统日历测试。
通知初始化暂时失败后可重试,日历服务异常在设置中解释并保持未启用。首次同步中断、尚无保存 ID 时,通过选定日历的专属标记恢复清理;清理失败持久保存待重试状态。
+11
View File
@@ -0,0 +1,11 @@
# 学校接入状态
当前首版提供自绘账号密码入口,以及学校官方页面进行验证码、二次验证和登录。认证使用系统 WebView 与学校原有提交及加密逻辑;密码不保存到本地文件,不发送到第三方服务器。退出会清除该 WebView 的 Cookie、缓存和本地存储,可选择保留或清除已导入课表。
已检查公开的 [统一身份认证页面](https://idas.uestc.edu.cn/authserver/login) 及脚本,核实表单结构和学校原有函数。登录前再次检查 HTTPS、域名、端口、路径和表单结构;页面变化时停止自动提交,仍可使用官方页面完成操作。
**尚未完成本人登录及真实课表自动识别。** [研究生课表查询页](https://yjsjy.uestc.edu.cn/pyxx/pygl/xskbcx/index/1) 需要本人会话,当前没有取得页面样本。解析器遇到当前未知页面明确提示“学校课表识别待联调,当前课表保持不变”,不会生成虚假课程或清空原课表。
后续在本人手机登录后,需要用脱敏课表页面核实:课程字段、单/双周、周次范围、连续节次、校区、空课表和会话失效。页面中学生姓名、学号、Cookie、令牌及密码应移除后才作为开发样本。取得样本后增加解析器与回归测试,再开放真实自动导入。
首版可体验内置示例,或通过 JSON 导入本人课程。JSON 导入先预览再确认,失败保留原数据;示例模式独立,不写手机日历或安排系统通知。
+10
View File
@@ -0,0 +1,10 @@
{
"schemaVersion": 1,
"isDemo": true,
"explicitlyEmpty": false,
"courses": [
{"id":"example-matrix","name":"矩阵论(示例)","teacher":"示例教师","room":"示例教室 A101","weekday":1,"startPeriod":1,"endPeriod":2,"weeks":[1,2,3,4,5,6,7,8]},
{"id":"example-english","name":"研究生英语(示例)","teacher":"示例教师","room":"示例教室 B202","weekday":3,"startPeriod":5,"endPeriod":6,"weeks":[1,3,5,7]},
{"id":"example-seminar","name":"学术研讨(示例)","teacher":"示例导师","room":"示例教室 C303","weekday":7,"startPeriod":9,"endPeriod":11,"weeks":[2,4,6,8]}
]
}
@@ -8,7 +8,7 @@
<application
android:label="河畔Everyday"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
android:icon="@drawable/ic_hepan_launcher">
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" android:exported="false" />
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver" android:exported="false">
<intent-filter>
@@ -111,9 +111,9 @@ class CalendarBridge(private val activity: Activity, messenger: BinaryMessenger)
}
val id = args["eventId"] as? String
if (id != null && ownership(id, key, calendarId)) {
val count = resolver.update(ContentUris.withAppendedId(Events.CONTENT_URI,id.toLong()), values,
"${Events.CUSTOM_APP_PACKAGE}=? AND ${Events.CUSTOM_APP_URI}=? AND ${Events.CALENDAR_ID}=?",
arrayOf(owner, marker(key), calendarId))
val count = resolver.update(Events.CONTENT_URI, values,
"${Events._ID}=? AND ${Events.CUSTOM_APP_PACKAGE}=? AND ${Events.CUSTOM_APP_URI}=? AND ${Events.CALENDAR_ID}=? AND ${Events.DELETED}=0",
arrayOf(id, owner, marker(key), calendarId))
check(count==1) { "日程已被修改" }
return id
}
@@ -121,7 +121,7 @@ class CalendarBridge(private val activity: Activity, messenger: BinaryMessenger)
}
private fun delete(id: String, key: String) {
if (!ownership(id,key)) return
resolver.delete(ContentUris.withAppendedId(Events.CONTENT_URI,id.toLong()),
"${Events.CUSTOM_APP_PACKAGE}=? AND ${Events.CUSTOM_APP_URI}=?", arrayOf(owner,marker(key)))
resolver.delete(Events.CONTENT_URI,
"${Events._ID}=? AND ${Events.CUSTOM_APP_PACKAGE}=? AND ${Events.CUSTOM_APP_URI}=?", arrayOf(id,owner,marker(key)))
}
}
@@ -0,0 +1,7 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:fillColor="#348F91" android:pathData="M0,0h108v108h-108z" />
<path android:fillColor="#FFFFFF" android:pathData="M28,29h52v43h-52z" />
<path android:fillColor="#348F91" android:pathData="M32,41h44v27h-44z" />
<path android:strokeColor="#FFFFFF" android:strokeWidth="4" android:strokeLineCap="round" android:pathData="M40,25v12M68,25v12M36,79c12,-9 24,9 36,0" />
<path android:fillColor="#FFFFFF" android:pathData="M40,49h8v8h-8zM60,49h8v8h-8z" />
</vector>
+128
View File
@@ -0,0 +1,128 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:hepan_everyday/app/app_controller.dart';
import 'package:hepan_everyday/main.dart';
import 'package:hepan_everyday/data/file_snapshot_store.dart';
import 'package:hepan_everyday/data/json_schedule_import.dart';
import 'package:hepan_everyday/domain/app_settings.dart';
import 'package:hepan_everyday/domain/course.dart';
import 'package:hepan_everyday/features/profile/import_preview.dart';
import '../test/support/fakes.dart';
import '../test/domain/schedule_engine_test.dart' show course;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUpAll(tzdata.initializeTimeZones);
testWidgets(
'offline import, preview cancellation, color settings and reopening preserve saved courses',
(tester) async {
final directory = await Directory.systemTemp.createTemp(
'hepan-device-test-',
);
final store = FileSnapshotStore(directory);
final controller = AppController(
store,
FakeNotifications(),
FakeCalendar(),
() => DateTime.utc(2026, 9, 9),
);
await controller.initialize();
await tester.pumpWidget(buildApplication(controller));
await tester.pumpAndSettle();
expect(find.bySemanticsLabel('课表'), findsOneWidget);
await tester.tap(find.bySemanticsLabel('我的'));
await tester.pumpAndSettle();
await tester.tap(find.text('课表设置'));
await tester.pumpAndSettle();
await tester.tap(find.text('单色'));
await tester.pumpAndSettle();
expect(controller.snapshot.settings.colorMode, ColorMode.single);
// Native file chooser itself is verified manually; preview uses the same UI as file import.
await tester.scrollUntilVisible(find.byKey(const Key('semester-weeks')),300,
scrollable:find.byType(Scrollable).last);
await tester.ensureVisible(find.text('学期开始日'));
await tester.pumpAndSettle();
await tester.tap(find.text('学期开始日'));await tester.pumpAndSettle();
await tester.tap(find.text('确定'));await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('semester-weeks')),'5');
await tester.ensureVisible(find.text('保存学期设置'));
await tester.tap(find.text('保存学期设置'));await tester.pumpAndSettle();
expect(controller.snapshot.settings.semester!.totalWeeks,5);
expect(controller.snapshot.settings.semester!.startDate,DateTime.utc(2026,9,9));
final draft = ImportDraft(
courses: [course(last: 2)],
explicitlyEmpty: false,
source: CourseSource.file,
parserVersion: 'device-json-v1',
);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (_) =>
ImportPreview(draft: draft, controller: controller),
),
child: const Text('预览文件'),
),
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('预览文件'));
await tester.pumpAndSettle();
await tester.tap(find.text('取消'));
await tester.pumpAndSettle();
expect(controller.snapshot.courses, isEmpty);
await tester.tap(find.text('预览文件'));
await tester.pumpAndSettle();
await tester.tap(find.text('确认导入'));
await tester.pumpAndSettle();
expect(controller.snapshot.courses.single.id, 'math');
await tester.pumpWidget(buildApplication(controller));
await tester.pumpAndSettle();
expect(find.text('矩阵论'), findsOneWidget);
final before = await File('${directory.path}/hepan_snapshot.json')
.readAsString();
await controller.showDemo();
await tester.pumpAndSettle();
expect(find.text('示例课表'), findsOneWidget);
expect(
await File('${directory.path}/hepan_snapshot.json').readAsString(),
before,
);
await controller.applyImport(
const ImportDraft(
courses: [],
explicitlyEmpty: false,
source: CourseSource.file,
parserVersion: 'bad',
),
confirmedEmpty: false,
);
expect(controller.snapshot.courses.single.id, 'math');
final reopened = AppController(
store,
FakeNotifications(),
FakeCalendar(),
controller.clock,
);
await reopened.initialize();
expect(reopened.snapshot.courses.single.id, 'math');
expect(reopened.snapshot.settings.colorMode, ColorMode.single);
await tester.pumpWidget(const SizedBox());
controller.dispose();
reopened.dispose();
await directory.delete(recursive: true);
},
);
}
@@ -0,0 +1,43 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:hepan_everyday/services/android_calendar_service.dart';
import 'package:hepan_everyday/domain/schedule_engine.dart';
import '../test/domain/schedule_engine_test.dart' show course;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets(
'native dedicated calendar creates updates deduplicates and deletes owned events',
(tester) async {
tzdata.initializeTimeZones();
await tester.pumpWidget(const MaterialApp(home: Scaffold()));
final gateway = MethodCalendarGateway();
final service = AndroidCalendarService(gateway);
expect(await service.requestAccess(),isTrue);
final calendars = await service.listWritableCalendars();
final selected = calendars.where(
(c) => c.name == 'Hepan_Integration_Test',
);
if (selected.isEmpty) {
fail('请先在专用模拟器建立 Hepan Integration Test 日历');
}
final id = selected.single.id;
final events = ScheduleEngine.occurrences([
course(last: 2),
], Semester(startDate: DateTime(2026, 9, 9), totalWeeks: 1));
var mapping = await service.sync(events, id, {});
expect(mapping, hasLength(1));
final original = mapping.values.single;
mapping = await service.sync(events, id, {}); // lost mapping recovery
expect(mapping.values.single, original);
expect(await gateway.ownedEvents(id), hasLength(1));
await gateway.delete(original, 'wrong-occurrence');
expect(await gateway.ownedEvents(id), hasLength(1));
await service.deleteOwned(mapping);
expect(await gateway.ownedEvents(id), isEmpty);
},
);
}
+12 -5
View File
@@ -170,8 +170,9 @@ class AppController extends ChangeNotifier {
}
calendarSyncError = null;
});
Future<void> enableCalendarFromUserAction(String calendarId) =>
_run(() async {
Future<void> enableCalendarFromUserAction(
String calendarId,
) => _run(() async {
if (isDemo) throw StateError('示例课表不会导入日历');
if (snapshot.settings.semester == null) throw StateError('请先设置学期');
if (!await calendar.requestAccess()) {
@@ -190,15 +191,17 @@ class AppController extends ChangeNotifier {
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),
);
await _save(snapshot.copyWith(settings: settings, calendarEventIds: ids));
calendarSyncError = null;
} catch (_) {
calendarSyncError = '日历同步失败,可重试';
@@ -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),
);
+48 -1
View File
@@ -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()) {
+37 -115
View File
@@ -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());
}
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';
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'),
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,
);
}
}
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),
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(
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),
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));
+13
View File
@@ -219,6 +219,11 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.1"
flutter_localizations:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_test:
dependency: "direct dev"
description: flutter
@@ -263,6 +268,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
intl:
dependency: transitive
description:
name: intl
sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867"
url: "https://pub.dev"
source: hosted
version: "0.20.3"
jni:
dependency: transitive
description:
+2
View File
@@ -7,6 +7,8 @@ environment:
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
webview_flutter: 4.14.1
flutter_local_notifications: 22.3.2
timezone: 0.11.1
+26
View File
@@ -9,6 +9,9 @@ import 'package:hepan_everyday/data/json_schedule_import.dart';
import '../support/fakes.dart';
import '../domain/schedule_engine_test.dart' show course;
import '../services/calendar_service_test.dart' show CalendarProvider;
import 'package:hepan_everyday/services/android_calendar_service.dart';
void main() {
setUpAll(tzdata.initializeTimeZones);
@@ -35,6 +38,29 @@ void main() {
);
});
tearDown(() => controller.dispose());
test('turning off after interrupted first sync cleans events even without saved IDs', () async {
store.value = store.value!.copyWith(
courses: [
course(id: 'a'),
course(id: 'b'),
],
);
final provider = CalendarProvider()..failAfterFirst = true;
final interrupted = AppController(
store,
notifications,
AndroidCalendarService(provider),
controller.clock,
);
await interrupted.initialize();
await interrupted.enableCalendarFromUserAction('local');
expect(interrupted.calendarSyncError, isNotNull);
expect(provider.records, hasLength(1));
provider.failAfterFirst = false;
await interrupted.disableCalendar(deleteEvents: true);
expect(provider.records, isEmpty);
interrupted.dispose();
});
test(
'failed calendar cleanup is retried after reopening while sync is off',
() async {
@@ -0,0 +1,38 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:hepan_everyday/services/local_notification_service.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('transient native initialization failure can be retried', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
AndroidFlutterLocalNotificationsPlugin.registerWith();
const channel = MethodChannel('dexterous.com/flutter/local_notifications');
var attempts = 0;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'initialize') {
attempts++;
if (attempts == 1) {
throw PlatformException(code: 'temporarily-unavailable');
}
return true;
}
if (call.method == 'getNotificationAppLaunchDetails') {
return {'notificationLaunchedApp': false};
}
return null;
});
addTearDown(() {
debugDefaultTargetPlatformOverride = null;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null);
});
final gateway = PluginReminderGateway();
await expectLater(gateway.initialize(), throwsA(isA<PlatformException>()));
await gateway.initialize();
expect(attempts, 2);
});
}
-30
View File
@@ -1,30 +0,0 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hepan_everyday/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
+39
View File
@@ -2,11 +2,44 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:hepan_everyday/app/hepan_app.dart';
import 'package:hepan_everyday/app/app_controller.dart';
import 'package:hepan_everyday/features/profile/settings_page.dart';
import 'package:hepan_everyday/services/calendar_service.dart';
import '../support/fakes.dart';
import 'navigation_test.dart' show uiController;
void main() {
setUpAll(tzdata.initializeTimeZones);
testWidgets('calendar provider failure is explained and keeps switch off', (
tester,
) async {
final controller = AppController(
MemoryStore(),
FakeNotifications(),
UnavailableCalendar(),
DateTime.now,
);
await controller.initialize();
await tester.pumpWidget(
MaterialApp(home: SettingsPage(controller: controller)),
);
await tester.pumpAndSettle();
await tester.scrollUntilVisible(
find.text('导入手机日历'),
250,
scrollable: find.byType(Scrollable).first,
);
await tester.ensureVisible(find.text('导入手机日历'));
await tester.pumpAndSettle();
await tester.tap(find.text('导入手机日历'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text('日历暂时不可用,请检查权限后重试'), findsOneWidget);
expect(controller.snapshot.settings.calendarEnabled, isFalse);
controller.dispose();
});
testWidgets(
'invalid semester weeks are rejected without changing saved data',
(tester) async {
@@ -57,3 +90,9 @@ void main() {
controller.dispose();
});
}
class UnavailableCalendar extends FakeCalendar {
@override
Future<List<DeviceCalendar>> listWritableCalendars() async =>
throw StateError('unavailable');
}
+56
View File
@@ -0,0 +1,56 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:hepan_everyday/main.dart';
import 'package:hepan_everyday/app/app_controller.dart';
import 'package:hepan_everyday/app/hepan_app.dart';
import 'package:hepan_everyday/domain/app_snapshot.dart';
import 'package:hepan_everyday/domain/app_settings.dart';
import 'package:hepan_everyday/domain/semester.dart';
import '../support/fakes.dart';
import '../domain/schedule_engine_test.dart' show course;
void main() {
setUpAll(tzdata.initializeTimeZones);
testWidgets(
'actual startup connects both tabs and reminder tap opens saved course',
(tester) async {
final selection = ValueNotifier<String?>(null);
final controller = AppController(
MemoryStore(
AppSnapshot(
courses: [course(last: 2)],
settings: AppSettings(
semester: Semester(
startDate: DateTime(2026, 9, 9),
totalWeeks: 5,
),
),
),
),
FakeNotifications(),
FakeCalendar(),
() => DateTime.utc(2026, 9, 8),
);
await controller.initialize();
await tester.pumpWidget(
buildApplication(controller, notificationSelection: selection),
);
await tester.pumpAndSettle();
expect(find.bySemanticsLabel('课表'), findsOneWidget);
expect(find.bySemanticsLabel('我的'), findsOneWidget);
await tester.tap(find.bySemanticsLabel('我的'));
await tester.pumpAndSettle();
selection.value = 'math/2026-09-09';
await tester.pumpAndSettle();
expect(find.text('知道了'), findsOneWidget);
expect(find.textContaining('08:30–10:05'), findsOneWidget);
await tester.tap(find.text('知道了'));
await tester.pumpAndSettle();
expect(find.byType(HepanApp), findsOneWidget);
controller.dispose();
selection.dispose();
},
);
}
+62
View File
@@ -0,0 +1,62 @@
// Device-only fixture entry point. Never used by the distributable APK.
import 'package:flutter/material.dart';
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:timezone/timezone.dart' as tz;
import 'package:hepan_everyday/main.dart' show buildApplication;
import 'package:hepan_everyday/app/app_controller.dart';
import 'package:hepan_everyday/domain/app_snapshot.dart';
import 'package:hepan_everyday/domain/app_settings.dart';
import 'package:hepan_everyday/domain/schedule_engine.dart';
import 'package:hepan_everyday/services/local_notification_service.dart';
import '../test/support/fakes.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
tzdata.initializeTimeZones();
final now = tz.TZDateTime.now(tz.getLocation('Asia/Shanghai'));
final date = DateTime.utc(now.year, now.month, now.day);
final course = Course(
id: 'native-probe',
name: '系统提醒验证(测试)',
teacher: '测试教师',
room: '测试教室',
weekday: now.weekday,
startPeriod: 1,
endPeriod: 2,
weeks: {1},
source: CourseSource.file,
);
final settings = AppSettings(
semester: Semester(startDate: date, totalWeeks: 1),
);
final selection = ValueNotifier<String?>(null);
final gateway = PluginReminderGateway(onTap: (key) => selection.value = key);
final service = LocalNotificationService(gateway);
const fireDelay = int.fromEnvironment(
'PROBE_DELAY_SECONDS',
defaultValue: 30,
);
final start = now.add(Duration(minutes: 15, seconds: fireDelay));
await service.reconcile(
[
CourseOccurrence(
key: 'native-probe/${date.toIso8601String().substring(0, 10)}',
course: course,
week: 1,
start: start,
end: start.add(const Duration(minutes: 95)),
),
],
settings,
now,
);
final controller = AppController(
MemoryStore(AppSnapshot(courses: [course], settings: settings)),
FakeNotifications(),
FakeCalendar(),
DateTime.now,
);
await controller.initialize();
runApp(buildApplication(controller, notificationSelection: selection));
}
+15
View File
@@ -0,0 +1,15 @@
param([string]$ToolchainRoot = 'C:/Users/david/Desktop/app/.tools')
$ErrorActionPreference = 'Stop'
$env:HEPAN_TOOLCHAIN_ROOT=$ToolchainRoot
. "$PSScriptRoot/android-env.ps1"
$projectRoot=Split-Path $PSScriptRoot -Parent
Push-Location "$projectRoot/mobile"
try {
flutter.bat build apk --debug
if($LASTEXITCODE -ne 0) { throw 'Android 构建失败,未复制 APK' }
$built=Join-Path (Get-Location) 'build/app/outputs/flutter-apk/app-debug.apk'
if(!(Test-Path -LiteralPath $built)) { throw '本次构建未生成 APK' }
New-Item -ItemType Directory -Force "$projectRoot/dist" | Out-Null
Copy-Item -LiteralPath $built -Destination "$projectRoot/dist/hepan-everyday-debug.apk" -Force
Get-Item -LiteralPath "$projectRoot/dist/hepan-everyday-debug.apk" | Select-Object FullName,Length,LastWriteTime
} finally { Pop-Location }