实现计划:状态常驻通知(7任务:服务+通道+notifier+两路写入+接线+验收)

This commit is contained in:
2026-11-23 21:14:07 +08:00
parent 6c7d04109b
commit c35682874e
@@ -0,0 +1,550 @@
# 状态常驻通知实现计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** App 登录后常驻一条锁屏/消息中心通知,展示最近一次数据拉取情况,App 被划掉后仍持续更新。
**Architecture:** 原生 Kotlin 前台服务(specialUse 类型)只负责渲染;数据采集方(Dart 轮询 + 原生 AlarmReceiver)写 SharedPreferences,服务 60 秒自刷新 + 原生意图即时刷新。启停经 MethodChannel(主引擎)由登录态与设置开关驱动。
**Tech Stack:** Android Foreground Service (Kotlin) + Flutter MethodChannel + shared_preferences
## Global Constraints
- 设备:Android 8.0+(minSdk 24),Pixel 6(Android 15)为验收机
- 前台服务类型必须用 `specialUse`(dataSync 在 Android 15 有一天 6 小时限制)
- prefs 跨语言约定:Dart `shared_preferences` 写 `FlutterSharedPreferences.xml`,key 自动加 `flutter.` 前缀;原生读写必须用文件名 `FlutterSharedPreferences`、key 前缀 `flutter.`
- 版本:本次发版 bump 到 `1.4.4+15`(pubspec + kAppVersion 同步)
- 构建参数固定:`--dart-define=API_BASE_URL=http://42.194.179.190:3003 --dart-define=API_FALLBACK_URLS=https://ceryuan.top --dart-define=JPUSH_APP_KEY=ba2236956024b8644a83e8c3`
- 文案:标题 `玄龙期货 · 监控中`;内容 `HH:MM 已拉取 · 暂无新信号` / `HH:MM 已拉取 · N 个新信号` / `HH:MM · 最新 {品种} {周期} {类型} {背离时间}`
## 设计微调(相对 spec 的实现层修正)
WorkManager 回调运行在独立后台 isolate,无法触达主引擎的 MethodChannel;因此**轮询侧只写 prefs**,由服务自身每 60 秒读 prefs 自刷新(代价可忽略);原生 AlarmReceiver 在同进程内,仍发 ACTION_REFRESH 即时刷新。
---
### Task 1: StatusService.kt 前台服务 + Manifest 声明
**Files:**
- Create: `app/android/app/src/main/kotlin/com/xuanlong/xuanlong_futures/StatusService.kt`
- Modify: `app/android/app/src/main/AndroidManifest.xml`
**Interfaces:**
- Produces: `StatusService`(actions: `start` / `refresh` / `stop`),原生侧通过 `Intent(this, StatusService::class.java).setAction(...)` 交互;prefs key `flutter.xl_status_text`
- [ ] **Step 1: 创建 StatusService.kt**
```kotlin
package com.xuanlong.xuanlong_futures
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/** 常驻状态通知:只负责渲染。采集方写 prefs(flutter.xl_status_text),本服务 60s 自刷新;
* 原生 AlarmReceiver 另发 ACTION_REFRESH 即时刷新。START_STICKY 保证被杀后自动重建。 */
class StatusService : Service() {
companion object {
const val CHANNEL_ID = "status_v1"
const val ACTION_START = "com.xuanlong.xuanlong_futures.status.START"
const val ACTION_REFRESH = "com.xuanlong.xuanlong_futures.status.REFRESH"
const val ACTION_STOP = "com.xuanlong.xuanlong_futures.status.STOP"
private const val NOTIF_ID = 20261123
private const val PREFS_FILE = "FlutterSharedPreferences"
private const val KEY_TEXT = "flutter.xl_status_text"
}
private val handler = Handler(Looper.getMainLooper())
private val tick = object : Runnable {
override fun run() {
refreshNotification()
handler.postDelayed(this, 60_000L)
}
}
override fun onCreate() {
super.onCreate()
createChannel()
startAsForeground()
handler.post(tick)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) {
handler.removeCallbacks(tick)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
return START_NOT_STICKY
}
refreshNotification()
return START_STICKY
}
override fun onDestroy() {
handler.removeCallbacks(tick)
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? = null
private fun startAsForeground() {
val n = buildNotification()
if (Build.VERSION.SDK_INT >= 29) {
startForeground(NOTIF_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
} else {
startForeground(NOTIF_ID, n)
}
}
private fun refreshNotification() {
getSystemService(NotificationManager::class.java).notify(NOTIF_ID, buildNotification())
}
private fun statusText(): String {
val raw = getSharedPreferences(PREFS_FILE, MODE_PRIVATE).getString(KEY_TEXT, null)
if (!raw.isNullOrEmpty()) return raw
return "${nowHm()} 监控中 · 等待首次数据拉取"
}
private fun nowHm(): String = SimpleDateFormat("HH:mm", Locale.CHINA).format(Date())
private fun buildNotification(): Notification {
val pi = PendingIntent.getActivity(
this, 20261123,
Intent(this, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
return Notification.Builder(this, CHANNEL_ID)
.setContentTitle("玄龙期货 · 监控中")
.setContentText(statusText())
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setContentIntent(pi)
.build()
}
private fun createChannel() {
val ch = NotificationChannel(CHANNEL_ID, "状态常驻", NotificationManager.IMPORTANCE_LOW).apply {
setShowBadge(false)
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
}
getSystemService(NotificationManager::class.java).createNotificationChannel(ch)
}
}
```
- [ ] **Step 2: Manifest 加权限与服务声明**
在 `AndroidManifest.xml` 的 `<uses-permission android:name="android.permission.WAKE_LOCK"/>` 之后插入:
```xml
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"/>
```
在 `<activity android:name=".AlarmActivity" .../>` 之后插入:
```xml
<service
android:name=".StatusService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="persistent_status_notification"/>
</service>
```
- [ ] **Step 3: 编译验证**
Run: `cd app && flutter build apk --debug 2>&1 | tail -3`
Expected: `✓ Built build/app/outputs/flutter-apk/app-debug.apk`
- [ ] **Step 4: Commit**
```bash
git add app/android/app/src/main/kotlin/com/xuanlong/xuanlong_futures/StatusService.kt app/android/app/src/main/AndroidManifest.xml
git commit -m "状态常驻通知(1/4):StatusService前台服务(specialUse,60s自刷新,START_STICKY)+Manifest声明"
```
---
### Task 2: MainActivity MethodChannel(start/stop)
**Files:**
- Modify: `app/android/app/src/main/kotlin/com/xuanlong/xuanlong_futures/MainActivity.kt`
**Interfaces:**
- Consumes: `StatusService`(Task 1)
- Produces: MethodChannel `xl_status_service`,方法 `start` / `stop`(Dart 侧 Task 3/6 调用)
- [ ] **Step 1: 读取现有 MainActivity.kt,保留现有内容,在 `configureFlutterEngine` 内追加**
```kotlin
import android.content.Intent
import androidx.core.content.ContextCompat
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// (保留文件里已有的其他配置代码)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "xl_status_service").setMethodCallHandler { call, result ->
when (call.method) {
"start" -> {
val i = Intent(this, StatusService::class.java).setAction(StatusService.ACTION_START)
ContextCompat.startForegroundService(this, i)
result.success(true)
}
"stop" -> {
startService(Intent(this, StatusService::class.java).setAction(StatusService.ACTION_STOP))
result.success(true)
}
else -> result.notImplemented()
}
}
}
}
```
(注意:实现时先 `cat` 现有文件;若已有 `configureFlutterEngine`,把 MethodChannel 块并入,不要覆盖已有逻辑。)
- [ ] **Step 2: 编译验证**
Run: `cd app && flutter build apk --debug 2>&1 | tail -3`
Expected: 构建成功
- [ ] **Step 3: Commit**
```bash
git add app/android/app/src/main/kotlin/com/xuanlong/xuanlong_futures/MainActivity.kt
git commit -m "状态常驻通知(2/4):MethodChannel xl_status_service 启停入口"
```
---
### Task 3: Dart status_notifier + 单元测试(TDD)
**Files:**
- Create: `app/lib/core/status/status_notifier.dart`
- Test: `app/test/status_notifier_test.dart`
**Interfaces:**
- Produces: `kStatusPrefsKey='xl_status_text'`;`String buildPollStatusText(int newCount, String hhmm)`;`Future<void> writePollStatus(String text)`;`Future<void> syncServiceWithAuth(bool loggedIn)`;`Future<void> setEnabled(bool on)`(prefs key `xl_status_enabled`,默认 true)
- [ ] **Step 1: 写失败测试**
```dart
import 'package:flutter_test/flutter_test.dart';
import 'package:xuanlong_futures/core/status/status_notifier.dart';
void main() {
group('buildPollStatusText', () {
test('无新信号', () {
expect(buildPollStatusText(0, '16:01'), '16:01 已拉取 · 暂无新信号');
});
test('有新信号', () {
expect(buildPollStatusText(2, '16:01'), '16:01 已拉取 · 2 个新信号');
});
});
}
```
- [ ] **Step 2: 跑测试确认失败**
Run: `cd app && flutter test test/status_notifier_test.dart`
Expected: FAIL(status_notifier.dart 不存在)
- [ ] **Step 3: 实现**
```dart
/// 常驻状态通知(Dart 侧):状态文本写入 + 服务启停。
///
/// prefs 跨语言约定见 spec:Dart 写 `xl_status_text`(shared_preferences 自动加
/// flutter. 前缀),原生 StatusService 读 `FlutterSharedPreferences` 的
/// `flutter.xl_status_text`,60s 自刷新渲染,无需 Dart 主动通知。
library;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
const kStatusPrefsKey = 'xl_status_text';
const kStatusEnabledKey = 'xl_status_enabled';
const _channel = MethodChannel('xl_status_service');
String buildPollStatusText(int newCount, String hhmm) =>
newCount > 0 ? '$hhmm 已拉取 · $newCount 个新信号' : '$hhmm 已拉取 · 暂无新信号';
Future<void> writePollStatus(String text) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(kStatusPrefsKey, text);
}
Future<bool> statusEnabled() async {
if (kIsWeb) return false;
final prefs = await SharedPreferences.getInstance();
return prefs.getBool(kStatusEnabledKey) ?? true;
}
/// 登录态变化时同步服务:登录=(开关开则)启动;登出=停止。
Future<void> syncServiceWithAuth(bool loggedIn) async {
if (kIsWeb) return;
try {
if (loggedIn && await statusEnabled()) {
await _channel.invokeMethod('start');
} else if (!loggedIn) {
await _channel.invokeMethod('stop');
}
} on PlatformException {
// 原生侧未就绪(热重载/旧包)时静默
} on MissingPluginException {
// Web 等无平台实现的环境
}
}
/// 设置页开关:保存偏好并立即启停。
Future<void> setEnabled(bool on) async {
if (kIsWeb) return;
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(kStatusEnabledKey, on);
try {
await _channel.invokeMethod(on ? 'start' : 'stop');
} on PlatformException {
// 同上
} on MissingPluginException {
// 同上
}
}
```
- [ ] **Step 4: 跑测试确认通过 + flutter analyze 无新告警**
Run: `cd app && flutter test test/status_notifier_test.dart && flutter analyze | tail -3`
Expected: All tests passed; No issues
- [ ] **Step 5: Commit**
```bash
git add app/lib/core/status/status_notifier.dart app/test/status_notifier_test.dart
git commit -m "状态常驻通知(3/4):Dart status_notifier(状态文本构建+启停通道)+单测"
```
---
### Task 4: 轮询写入状态文本
**Files:**
- Modify: `app/lib/core/background/background_poll.dart`(`_poll` 尾部)
**Interfaces:**
- Consumes: `writePollStatus` / `buildPollStatusText`(Task 3)
- [ ] **Step 1: `_poll()` 中统计本轮新信号并写入**
现有循环里 `shown.add(sid)` 之前维护计数:循环前 `var newCount = 0;`,`if (shown.contains(sid)) continue;` 之后 `if (m['is_new'] != true) continue;` 之后加 `newCount++;`。函数末尾(`setStringList` 之后)加:
```dart
final now = DateTime.now();
final hhmm =
'${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
await writePollStatus(buildPollStatusText(newCount, hhmm));
// 注意:后台 isolate 无法触达主引擎 MethodChannel,无需发 refresh——
// StatusService 60s 自刷新会读到新文本。
```
import 增加 `import '../status/status_notifier.dart';`
- [ ] **Step 2: flutter analyze**
Run: `cd app && flutter analyze | tail -3`
Expected: No issues
- [ ] **Step 3: Commit**
```bash
git add app/lib/core/background/background_poll.dart
git commit -m "状态常驻通知(4/4a):轮询完成后写入常驻状态文本"
```
---
### Task 5: AlarmReceiver 原生写入 + 即时刷新
**Files:**
- Modify: `app/android/app/src/main/kotlin/com/xuanlong/xuanlong_futures/AlarmReceiver.kt`(`onMessage` 内)
**Interfaces:**
- Consumes: `StatusService.ACTION_REFRESH`(Task 1)
- [ ] **Step 1: `onMessage` 中,在 `notifyFullScreen(...)`/前台分支之后统一追加**
(放在 type 判断之后、所有分支之后,保证测试消息即使走前台拉起路径也更新状态)
```kotlin
updatePersistentStatus(extras.optString("kind"), extras.optString("symbol"),
extras.optString("interval"), extras.optString("divergence_time"))
```
新增私有方法:
```kotlin
/** 信号到达即更新常驻状态文本(flutter.xl_status_text)并即时刷新前台服务。 */
private fun updatePersistentStatus(kind: String, symbol: String, interval: String, divTime: String) {
val hm = java.text.SimpleDateFormat("HH:mm", java.util.Locale.CHINA).format(java.util.Date())
val label = labelOf(if (kind == "digest") "digest" else kind)
val body = if (kind == "digest") {
"$hm · 最新:$label"
} else {
"$hm · 最新 $symbol $interval $label ${divTime.takeLast(5)}"
}
getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE)
.edit().putString("flutter.xl_status_text", body).apply()
startService(Intent(this, StatusService::class.java).setAction(StatusService.ACTION_REFRESH))
}
```
(需 import `android.content.Intent`——文件已有。)
- [ ] **Step 2: 编译验证**
Run: `cd app && flutter build apk --debug 2>&1 | tail -3`
Expected: 构建成功
- [ ] **Step 3: Commit**
```bash
git add app/android/app/src/main/kotlin/com/xuanlong/xuanlong_futures/AlarmReceiver.kt
git commit -m "状态常驻通知(4/4b):信号到达原生更新常驻状态并即时刷新"
```
---
### Task 6: 登录态与设置页接线
**Files:**
- Modify: `app/lib/main.dart`(`_XuanlongAppState.build` 的 `ref.listen(authStageProvider, ...)` 块 + 启动初始化块)
- Modify: `app/lib/features/settings/settings_page.dart`(新增卡片)
**Interfaces:**
- Consumes: `syncServiceWithAuth` / `setEnabled` / `statusEnabled`(Task 3)
- [ ] **Step 1: main.dart 登录态接线**
`ref.listen(authStageProvider, (_, __) {...})` 块内追加:
```dart
final stage = ref.read(authStageProvider);
// 状态常驻通知:登录启动(开关默认开)、登出停止
() async {
try {
await syncServiceWithAuth(stage == AuthStage.loggedIn);
} catch (_) {}
}();
```
import 增加 `import 'core/status/status_notifier.dart';` 与 `AuthStage`(auth_controller 已 import,需补 show `AuthStage`)。
- [ ] **Step 2: settings_page 新增卡片**
在 `_alarmGuideCard()` 之前插入调用 `_statusCard()`,实现(沿用 `_alarmGuideCard` 的容器样式):
```dart
Widget _statusCard() {
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: XlColors.surface,
borderRadius: BorderRadius.circular(XlRadius.card),
border: Border.all(color: XlColors.border),
),
child: FutureBuilder<bool>(
future: statusEnabled(),
builder: (context, snap) {
final on = snap.data ?? true;
return Row(
children: [
const Icon(Icons.monitor_heart, size: 20, color: XlColors.goldLight),
const SizedBox(width: 10),
const Expanded(
child: Text('状态常驻通知\n锁屏与消息中心展示最新拉取状态',
style: TextStyle(fontSize: 13)),
),
Switch(value: on, onChanged: (v) async {
await setEnabled(v);
// 强制刷新本卡片
(context as Element?)?.markNeedsBuild();
}),
],
);
},
),
);
}
```
(实现时若 FutureBuilder 刷新生涩,可用 setState 包装成 StatefulWidget;以现有页面代码风格为准。)
- [ ] **Step 3: flutter analyze**
Run: `cd app && flutter analyze | tail -3`
Expected: No issues
- [ ] **Step 4: Commit**
```bash
git add app/lib/main.dart app/lib/features/settings/settings_page.dart
git commit -m "状态常驻通知(4/4c):登录态自动启停+设置页开关"
```
---
### Task 7: 发版构建 + Pixel 6 真机验收
**Files:**
- Modify: `app/pubspec.yaml`(`version: 1.4.3+14` → `version: 1.4.4+15`)
- Modify: `app/lib/features/misc/app_updater.dart`(`kAppVersion = '1.4.3'` → `'1.4.4'`)
- [ ] **Step 1: 版本号 bump + release 构建**
Run: `flutter build apk --release --dart-define=API_BASE_URL=http://42.194.179.190:3003 --dart-define=API_FALLBACK_URLS=https://ceryuan.top --dart-define=JPUSH_APP_KEY=ba2236956024b8644a83e8c3`
- [ ] **Step 2: adb 覆盖安装并启动**
```bash
adb install -r app/build/app/outputs/flutter-apk/app-release.apk
adb shell monkey -p com.xuanlong.xuanlong_futures -c android.intent.category.LAUNCHER 1
```
- [ ] **Step 3: 逐项真机验证(dumpsys + 肉眼)**
```bash
adb shell dumpsys notification --noredact | grep -A6 "status_v1"
```
验收清单:
1. 登录后通知出现(ongoing=true,IMPORTANCE_LOW)
2. 划掉 App(`adb shell input keyevent KEYCODE_APP_SWITCH` + 清后台)后通知仍在,60 秒内文本刷新
3. 管理台发测试信号 → 手机弹闹钟,同时常驻通知文本变「最新 …」
4. 设置关开关 → 通知消失;重开 → 恢复
5. 锁屏状态可见
- [ ] **Step 4: 生产包落位 + 提交推送**
```bash
cp app/build/app/outputs/flutter-apk/app-release.apk server/data/apk/xuanlong-1.4.4.apk
git add -A && git commit -m "状态常驻通知:版本升至1.4.4+15" && git push gitea main
```