65 lines
1.8 KiB
Dart
65 lines
1.8 KiB
Dart
|
|
/// 应用内更新下载期间的「屏幕常亮」开关。
|
|||
|
|
///
|
|||
|
|
/// - Android:走原生通道 `seqstudio/docs` 的 `keepScreenOn`(窗口 flag);
|
|||
|
|
/// - Windows:`SetThreadExecutionState`(FFI,禁止系统休眠与关屏);
|
|||
|
|
/// - 其它平台:空操作。任何失败都不影响更新流程(静默)。
|
|||
|
|
library;
|
|||
|
|
|
|||
|
|
import 'dart:ffi';
|
|||
|
|
import 'dart:io';
|
|||
|
|
|
|||
|
|
import 'package:flutter/services.dart';
|
|||
|
|
|
|||
|
|
/// 屏幕常亮(引用计数:enable / disable 配对;嵌套安全)。
|
|||
|
|
class KeepAwake {
|
|||
|
|
KeepAwake._();
|
|||
|
|
|
|||
|
|
static const MethodChannel _channel = MethodChannel('seqstudio/docs');
|
|||
|
|
static int _count = 0;
|
|||
|
|
|
|||
|
|
/// 开启(重复开启只生效一次)。
|
|||
|
|
static Future<void> enable() async {
|
|||
|
|
_count++;
|
|||
|
|
if (_count != 1) return;
|
|||
|
|
await _apply(true);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// 关闭(配对 [enable])。
|
|||
|
|
static Future<void> disable() async {
|
|||
|
|
if (_count > 0) _count--;
|
|||
|
|
if (_count != 0) return;
|
|||
|
|
await _apply(false);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// 强制关闭(对话框销毁等兜底场景)。
|
|||
|
|
static Future<void> forceOff() async {
|
|||
|
|
_count = 0;
|
|||
|
|
await _apply(false);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
static Future<void> _apply(bool on) async {
|
|||
|
|
try {
|
|||
|
|
if (Platform.isAndroid) {
|
|||
|
|
await _channel.invokeMethod<bool>(
|
|||
|
|
'keepScreenOn',
|
|||
|
|
<String, dynamic>{'on': on},
|
|||
|
|
);
|
|||
|
|
} else if (Platform.isWindows) {
|
|||
|
|
_applyWindows(on);
|
|||
|
|
}
|
|||
|
|
} catch (_) {
|
|||
|
|
// 保持常亮失败不应中断更新。
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
static void _applyWindows(bool on) {
|
|||
|
|
final DynamicLibrary lib = DynamicLibrary.open('kernel32.dll');
|
|||
|
|
final int Function(int) setState =
|
|||
|
|
lib.lookupFunction<Uint32 Function(Uint32), int Function(int)>(
|
|||
|
|
'SetThreadExecutionState',
|
|||
|
|
);
|
|||
|
|
// ES_CONTINUOUS |(ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED)
|
|||
|
|
setState(on ? 0x80000003 : 0x80000000);
|
|||
|
|
}
|
|||
|
|
}
|