Reduce Android and iOS background work

This commit is contained in:
shen
2026-12-03 16:46:29 -08:00
parent 9e05f1ad93
commit e68cb6c909
12 changed files with 189 additions and 60 deletions
@@ -19,12 +19,10 @@ import java.util.concurrent.TimeUnit
// All service state is confined to `worker`: requests from the activity, the
// health tick, network callbacks and route updates run there one at a time.
// Status reads a snapshot refreshed after every worker task, so a slow TUN
// rebuild never stalls the UI poll.
// Full telemetry is collected only when requested by the UI.
class MeshVpnService : VpnService() {
companion object { @Volatile var current: MeshVpnService? = null; private set }
private val worker = ScheduledThreadPoolExecutor(1)
@Volatile private var statusSnapshot: String? = null
// Invalidates the route watcher thread of a previous session.
@Volatile private var watchSession = 0
private var handle = 0L
@@ -56,18 +54,15 @@ class MeshVpnService : VpnService() {
.setSmallIcon(R.drawable.ic_stat_meshport).setContentIntent(open).setOngoing(true).build())
// Health tick. Route changes normally arrive from the watcher thread;
// the generation check here only covers a watcher that has exited.
worker.scheduleWithFixedDelay({
try { tick() } finally { refreshStatus() }
}, 2, 2, TimeUnit.SECONDS)
worker.scheduleWithFixedDelay({ tick() }, 2, 2, TimeUnit.SECONDS)
}
private fun tick() {
if (running) try {
if (unified) {
check(proxyCall(JSONObject().put("op","status")).getJSONObject("data").getString("state") == "Running")
check(proxyCall(JSONObject().put("op","health")).getJSONObject("data").getString("state") == "Running")
if (!meshEnabled) return
}
val data = native(JSONObject().put("op", "status")).getJSONObject("data")
val health = data.optJSONObject("health") ?: JSONObject()
val health = native(JSONObject().put("op", "health")).getJSONObject("data")
val routable = health.optBoolean(if (unified) "mesh_routable" else "engine_running")
if (!routable) {
// Combined mode keeps the proxy and drops mesh routes;
@@ -79,18 +74,14 @@ class MeshVpnService : VpnService() {
}
return
}
val platform = data.getJSONObject("platform_network")
applyRoutes(handle, platform.getLong("route_generation"), strings(platform.getJSONArray("mesh_cidrs")))
val routes = health.getJSONObject("routes")
applyRoutes(handle, routes.getLong("generation"), strings(routes.getJSONArray("cidrs")))
} catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() }
}
/** Runs [block] on `worker`, then republishes the status snapshot. */
private fun onWorker(block: () -> Unit) = worker.execute { try { block() } finally { refreshStatus() } }
private fun refreshStatus() {
statusSnapshot = try { dispatch(JSONObject().put("op", "status")).toString() } catch (_: Exception) { null }
}
private fun onWorker(block: () -> Unit) = worker.execute { block() }
/** Runs on `worker`. Ignores stale updates from a previous context. */
private fun applyRoutes(context: Long, generation: Long, cidrs: List<String>) {
if (!running || context != handle || generation == routeGeneration) return
if (!running || context != handle || generation <= routeGeneration) return
if (cidrs != meshCidrs) { if (unified) restartProxy(cidrs) else rebuild(cidrs) }
routeGeneration = generation
}
@@ -102,7 +93,7 @@ class MeshVpnService : VpnService() {
while (session == watchSession) {
val reply = try {
JSONObject(NativeBridge.call(context, JSONObject().put("op", "wait_routes")
.put("after_generation", generation).put("timeout_ms", 10000).toString()))
.put("after_generation", generation).put("timeout_ms", 30000).toString()))
} catch (_: Exception) { return@Thread }
// An error means the context is gone; a stopped network is
// left to the health tick, which knows the session's mode.
@@ -135,23 +126,10 @@ class MeshVpnService : VpnService() {
check(response.optBoolean("ok")) { response.optString("error", "Native request failed") }
return response
}
/**
* Callable from any thread; [reply] runs on `worker`, or immediately for a
* status answered from the snapshot. Never blocks the caller.
*/
/** Queues a request without blocking the caller. [reply] runs on the worker. */
fun request(request: JSONObject, reply: (Result<JSONObject>) -> Unit) {
val snapshot = statusSnapshot
if (request.optString("op") == "status" && snapshot != null) {
reply(Result.success(JSONObject(snapshot))); return
}
try {
// Republish the snapshot before replying, so the caller's next
// status already reflects this operation.
worker.execute {
val result = runCatching { dispatch(request) }
refreshStatus()
reply(result)
}
worker.execute { reply(runCatching { dispatch(request) }) }
} catch (error: java.util.concurrent.RejectedExecutionException) {
reply(Result.failure(IllegalStateException("VPN service is stopping")))
}
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'network_telemetry.dart';
import 'ui_lifecycle.dart';
class LiveDetailPage extends StatefulWidget {
final String title;
@@ -12,11 +13,25 @@ class LiveDetailPage extends StatefulWidget {
State<LiveDetailPage> createState() => _LiveDetailPageState();
}
class _LiveDetailPageState extends State<LiveDetailPage> {
class _LiveDetailPageState extends State<LiveDetailPage>
with WidgetsBindingObserver {
Timer? timer;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
updateTimer(WidgetsBinding.instance.lifecycleState);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (usesMobileLifecycle) updateTimer(state);
}
void updateTimer(AppLifecycleState? state) {
timer?.cancel();
timer = null;
if (!shouldRefreshUi(state)) return;
timer = Timer.periodic(const Duration(seconds: 2), (_) {
if (mounted) setState(() {});
});
@@ -24,6 +39,7 @@ class _LiveDetailPageState extends State<LiveDetailPage> {
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
timer?.cancel();
super.dispose();
}
+51 -16
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart' show defaultTargetPlatform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
@@ -12,6 +13,7 @@ import 'configuration_pages.dart';
import 'detail_pages.dart';
import 'runtime_diagnostics.dart';
import 'proxy_speed_test.dart';
import 'ui_lifecycle.dart';
class LabScreen extends StatefulWidget {
const LabScreen({super.key, this.initializeNative = true});
@@ -20,7 +22,7 @@ class LabScreen extends StatefulWidget {
State<LabScreen> createState() => _LabScreenState();
}
class _LabScreenState extends State<LabScreen> {
class _LabScreenState extends State<LabScreen> with WidgetsBindingObserver {
MeshPortClient? client, applicationClient, systemClient;
MacSystemVpnSession? macVpnSession;
bool legacyMigrationPending = false;
@@ -48,6 +50,11 @@ class _LabScreenState extends State<LabScreen> {
String? loadedConfig, loadedForm;
static const vpnChannel = MethodChannel('meshport/system_vpn');
Timer? timer, subscriptionTimer;
bool initialized = false;
bool get uiActive => shouldRefreshUi(WidgetsBinding.instance.lifecycleState);
bool get detailedDiagnostics =>
!(Platform.isAndroid || Platform.isIOS) ||
const bool.fromEnvironment('MESHPORT_DETAILED_DIAGNOSTICS');
bool subscriptionUpdating = false;
String? savedProxyJson;
final subscriptionRetry = <String, DateTime>{};
@@ -98,6 +105,7 @@ class _LabScreenState extends State<LabScreen> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
if (widget.initializeNative) {
unawaited(initialize());
}
@@ -105,7 +113,7 @@ class _LabScreenState extends State<LabScreen> {
Future<void> initialize() async {
try {
log('客户端启动 · ${Platform.operatingSystem} · 代理诊断日志已开启');
log('客户端启动 · ${Platform.operatingSystem}');
// A --dart-define wins; the process environment serves `flutter test`
// and development runs. Release builds use the bundled library.
const defined = String.fromEnvironment('MESHPORT_LIBRARY');
@@ -193,8 +201,12 @@ class _LabScreenState extends State<LabScreen> {
proxyProfile.entry = runtimeMode;
}
singBoxEnabled = proxyProfile.proxyEnabled;
final diagnostics = await opened.enableDiagnostics();
log(diagnostics['enabled'] == true ? '穿透详细日志采集已开启' : '穿透日志未接管:宿主已有日志订阅器');
if (detailedDiagnostics) {
final diagnostics = await opened.enableDiagnostics();
log(
diagnostics['enabled'] == true ? '穿透详细日志采集已开启' : '穿透日志未接管:宿主已有日志订阅器',
);
}
if (profileSupported) await checkLocalProfileMigration();
if (Platform.isAndroid) {
final snapshot = await androidVpnRequest({'op': 'status'});
@@ -214,10 +226,6 @@ class _LabScreenState extends State<LabScreen> {
await refresh();
}
}
subscriptionTimer = Timer.periodic(
const Duration(minutes: 1),
(_) => unawaited(updateDueSubscriptions()),
);
if (Platform.isMacOS || Platform.isAndroid) {
try {
final preferences = await vpnChannel.invokeMapMethod<String, dynamic>(
@@ -244,12 +252,9 @@ class _LabScreenState extends State<LabScreen> {
log('自动连接未完成,请手动连接并检查授权');
}
}
unawaited(updateDueSubscriptions());
timer = Timer.periodic(const Duration(seconds: 2), (_) {
if (!busy) {
unawaited(refresh());
}
});
if (!mounted) return;
initialized = true;
updateUiTimers();
} catch (e) {
if (mounted) {
setState(() => error = '原生库未加载,请先构建并指定 MESHPORT_LIBRARY。$e');
@@ -257,6 +262,34 @@ class _LabScreenState extends State<LabScreen> {
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (defaultTargetPlatform == TargetPlatform.iOS &&
(state == AppLifecycleState.hidden ||
state == AppLifecycleState.paused ||
state == AppLifecycleState.detached)) {
cancel = true;
if (speedTesting) proxySpeedTest.cancel();
}
if (usesMobileLifecycle && initialized) updateUiTimers();
}
void updateUiTimers() {
timer?.cancel();
subscriptionTimer?.cancel();
timer = subscriptionTimer = null;
if (!uiActive) return;
if (!busy) unawaited(refresh());
unawaited(updateDueSubscriptions());
timer = Timer.periodic(const Duration(seconds: 2), (_) {
if (!busy) unawaited(refresh());
});
subscriptionTimer = Timer.periodic(
const Duration(minutes: 1),
(_) => unawaited(updateDueSubscriptions()),
);
}
Future<Map<String, dynamic>> androidVpnRequest(
Map<String, dynamic> request,
) async {
@@ -309,7 +342,7 @@ class _LabScreenState extends State<LabScreen> {
}
Future<void> refresh() async {
if (refreshing) return;
if (refreshing || !uiActive) return;
refreshing = true;
try {
final next = client == applicationClient && proxySession != null
@@ -624,7 +657,7 @@ class _LabScreenState extends State<LabScreen> {
),
)).acquire();
try {
await opened.enableDiagnostics();
if (detailedDiagnostics) await opened.enableDiagnostics();
if (unified) {
await diagnosticStage(
'启动统一 VPN 代理',
@@ -859,6 +892,7 @@ class _LabScreenState extends State<LabScreen> {
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
cancel = true;
proxySpeedTest.cancel();
timer?.cancel();
@@ -1496,6 +1530,7 @@ class _LabScreenState extends State<LabScreen> {
);
Future<void> updateDueSubscriptions() async {
if (!mounted ||
!uiActive ||
busy ||
subscriptionUpdating ||
proxySavesPending > 0 ||
@@ -0,0 +1,9 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
bool get usesMobileLifecycle =>
defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS;
bool shouldRefreshUi(AppLifecycleState? state) =>
!usesMobileLifecycle || state == null || state == AppLifecycleState.resumed;
@@ -0,0 +1,33 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/detail_pages.dart';
void main() {
testWidgets(
'iOS detail polling pauses when hidden and resumes on return',
(tester) async {
final binding = tester.binding;
binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
var builds = 0;
await tester.pumpWidget(
MaterialApp(
home: LiveDetailPage(title: '详情', builder: () => Text('${++builds}')),
),
);
final initial = builds;
await tester.pump(const Duration(seconds: 2));
expect(builds, initial + 1);
binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
final beforeHidden = builds;
await tester.pump(const Duration(seconds: 10));
expect(builds, beforeHidden);
binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pump(const Duration(seconds: 2));
expect(builds, beforeHidden + 1);
await tester.pumpWidget(const SizedBox.shrink());
},
variant: const TargetPlatformVariant({TargetPlatform.iOS}),
);
}