修复版本管理整包更新无法弹出的问题
完成集成新的登录接口的更换使用 完成集成用户的场站列表接口 完成开发设计选择场站项为全局属性 完成我的页面的个人信息的集成和详情页面的开发 完成设备页面的中无人机机场的列表接口对接入和个项页面的布局的优化 完成设备页面的中无人机机场的详情接口的对接和使用和页面的更新布局
This commit is contained in:
@@ -16,6 +16,15 @@ class HttpApiConsts {
|
||||
// 切换设备
|
||||
static const String switchDevice = "$baseUrl/forward/device/switchDevice";
|
||||
|
||||
// 获取光伏电站列表
|
||||
static const String getSiteList = "$baseUrl/system/site/list";
|
||||
|
||||
// 获取场站下的无人机机场列表
|
||||
static const String getSiteUAVList = "$baseUrl/iot/UAV/getSiteUAVList";
|
||||
|
||||
// 获取UAV状态详情
|
||||
static const String getUAVState = "$baseUrl/iot/UAV/getUAVState";
|
||||
|
||||
|
||||
// 获取设备位置
|
||||
static const String getDeviceLocation = "$baseUrl/iot/device/userDevice";
|
||||
|
||||
@@ -57,15 +57,27 @@ import '../../features/remote_control/data/datasources/remote_tcp_datasource.dar
|
||||
import '../../features/remote_control/domain/usecase/remote_control_usecase.dart';
|
||||
import '../../features/remote_control/presentation/bloc/remote_control_cubit.dart';
|
||||
import '../../features/v2/home/data/datasources/home_remote_datasource.dart';
|
||||
import '../../features/v2/home/data/datasources/site_datasource.dart';
|
||||
import '../../features/v2/home/data/datasources/site_datasource_impl.dart';
|
||||
import '../../features/v2/home/data/repositories/home_repository_impl.dart';
|
||||
import '../../features/v2/home/data/repositories/site_repository_impl.dart';
|
||||
import '../../features/v2/home/domain/repositories/home_repository.dart';
|
||||
import '../../features/v2/home/domain/repositories/site_repository.dart';
|
||||
import '../../features/v2/home/domain/usecases/get_home_data_usecase.dart';
|
||||
import '../../features/v2/home/domain/usecases/get_site_list_usecase.dart';
|
||||
import '../../features/v2/home/presentation/bloc/home_v2_bloc.dart';
|
||||
import '../../features/v2/site/presentation/cubit/site_cubit.dart';
|
||||
import '../../features/v2/device_list/data/datasources/device_remote_datasource.dart' as device_v2;
|
||||
import '../../features/v2/device_list/data/repositories/device_repository_impl.dart' as device_v2_repo;
|
||||
import '../../features/v2/device_list/domain/repositories/device_repository.dart' as device_v2_domain;
|
||||
import '../../features/v2/device_list/domain/usecases/get_device_status_data_usecase.dart' as device_v2_usecase;
|
||||
import '../../features/v2/device_list/presentation/bloc/device_status_bloc.dart' as device_v2_bloc;
|
||||
import '../../features/v2/device_list/data/datasources/drone_station_datasource.dart';
|
||||
import '../../features/v2/device_list/data/datasources/drone_station_datasource_impl.dart';
|
||||
import '../../features/v2/device_list/data/repositories/drone_station_repository_impl.dart';
|
||||
import '../../features/v2/device_list/domain/repositories/drone_station_repository.dart';
|
||||
import '../../features/v2/device_list/domain/usecases/get_drone_station_list_usecase.dart';
|
||||
import '../../features/v2/device_list/presentation/bloc/drone_station_bloc.dart';
|
||||
import '../../features/v2/waring_center/data/datasources/alarm_remote_datasource.dart';
|
||||
import '../../features/v2/waring_center/data/datasources/impl/alarm_remote_datasource_impl.dart';
|
||||
import '../../features/v2/waring_center/data/repositories/alarm_repository_impl.dart';
|
||||
@@ -204,7 +216,13 @@ Future<void> init() async {
|
||||
sl.registerLazySingleton<HomeRemoteDataSource>(() => HomeRemoteDataSourceImpl());
|
||||
sl.registerLazySingleton<HomeRepository>(() => HomeRepositoryImpl(sl()));
|
||||
sl.registerLazySingleton<GetHomeDataUseCase>(() => GetHomeDataUseCase(sl()));
|
||||
sl.registerFactory<HomeV2Bloc>(() => HomeV2Bloc(sl()));
|
||||
|
||||
// Site (场站)
|
||||
sl.registerLazySingleton<SiteDataSource>(() => SiteDataSourceImpl(sl<Dio>()));
|
||||
sl.registerLazySingleton<SiteRepository>(() => SiteRepositoryImpl(sl()));
|
||||
sl.registerLazySingleton<GetSiteListUseCase>(() => GetSiteListUseCase(sl()));
|
||||
|
||||
sl.registerFactory<HomeV2Bloc>(() => HomeV2Bloc(sl(), sl(), sl<AppUserCubit>(), sl<SiteCubit>()));
|
||||
|
||||
/// Device Status V2
|
||||
sl.registerLazySingleton<device_v2.DeviceRemoteDataSource>(() => device_v2.DeviceRemoteDataSourceImpl());
|
||||
@@ -212,6 +230,13 @@ Future<void> init() async {
|
||||
sl.registerLazySingleton<device_v2_usecase.GetDeviceStatusDataUseCase>(() => device_v2_usecase.GetDeviceStatusDataUseCase(repository: sl()));
|
||||
sl.registerFactory<device_v2_bloc.DeviceStatusBloc>(() => device_v2_bloc.DeviceStatusBloc(sl()));
|
||||
|
||||
/// Drone Station V2
|
||||
sl.registerLazySingleton<DroneStationDataSource>(() => DroneStationDataSourceImpl(sl<Dio>()));
|
||||
sl.registerLazySingleton<DroneStationRepository>(() => DroneStationRepositoryImpl(sl()));
|
||||
sl.registerLazySingleton<GetDroneStationListUseCase>(() => GetDroneStationListUseCase(sl()));
|
||||
sl.registerLazySingleton<GetUAVDetailUseCase>(() => GetUAVDetailUseCase(sl()));
|
||||
sl.registerFactory<DroneStationBloc>(() => DroneStationBloc(sl(), sl()));
|
||||
|
||||
/// Alarm Center V2
|
||||
sl.registerLazySingleton<AlarmRemoteDataSource>(() => AlarmRemoteDataSourceImpl());
|
||||
sl.registerLazySingleton<AlarmRepository>(() => AlarmRepositoryImpl(sl()));
|
||||
@@ -226,6 +251,9 @@ Future<void> init() async {
|
||||
/// 5. 状态管理 (Cubit/Bloc)
|
||||
sl.registerLazySingleton(() => AppUserCubit()); // AuthCubit 依赖它,必须先注册
|
||||
|
||||
// 🔥 SiteCubit (全局共享,持久化选中场站)
|
||||
sl.registerLazySingleton(() => SiteCubit(sl<SharedPreferences>()));
|
||||
|
||||
// 🔥 语言管理 Cubit (单例)
|
||||
sl.registerLazySingleton(() => LocaleCubit());
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ class UserEntity extends Equatable {
|
||||
final String username;
|
||||
final String nickname;
|
||||
final String token;
|
||||
final int orgId; // 组织ID,用于获取场站列表
|
||||
final String? avatar;
|
||||
final String? email;
|
||||
final String? phone;
|
||||
@@ -14,6 +15,7 @@ class UserEntity extends Equatable {
|
||||
required this.username,
|
||||
required this.nickname,
|
||||
required this.token,
|
||||
required this.orgId,
|
||||
this.avatar,
|
||||
this.email,
|
||||
this.phone,
|
||||
@@ -26,6 +28,7 @@ class UserEntity extends Equatable {
|
||||
nickname,
|
||||
avatar,
|
||||
token,
|
||||
orgId,
|
||||
email,
|
||||
phone,
|
||||
];
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
import 'package:open_file/open_file.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'version_check_service.dart';
|
||||
import 'update_state.dart';
|
||||
|
||||
@@ -81,7 +84,7 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载并安装完整 APK
|
||||
/// 自动下载并安装 APK(App 内下载)
|
||||
Future<void> downloadAndInstallApk(String apkUrl) async {
|
||||
emit(const UpdateDownloading(0.0, isPatch: false));
|
||||
|
||||
@@ -93,16 +96,19 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
});
|
||||
|
||||
if (apkPath != null) {
|
||||
emit(const UpdateInstalling(isPatch: false));
|
||||
|
||||
// 🔥 整包更新后,清除补丁版本记录
|
||||
_logger.i('✅ APK 下载完成: $apkPath');
|
||||
// 🔥 关键:先清理版本号记录,并等待用户看到提示
|
||||
emit(const UpdateClearingVersion());
|
||||
_logger.i('🗑️ 开始清除补丁版本记录');
|
||||
await _versionService.clearPatchVersionInfo();
|
||||
_logger.i('✅ 补丁版本记录已清除');
|
||||
|
||||
// 打开 APK 文件,触发系统安装界面
|
||||
final result = await OpenFile.open(apkPath);
|
||||
_logger.i('📦 安装结果: ${result.message}');
|
||||
|
||||
emit(UpdateSuccess());
|
||||
// 🔥 短暂延迟,让用户看到清理完成的提示
|
||||
await Future.delayed(const Duration(milliseconds: 800));
|
||||
|
||||
// 🔥 直接调起系统安装页面,不再等待用户点击
|
||||
_logger.i('📦 自动调起系统安装页面');
|
||||
await triggerInstall(apkPath);
|
||||
} else {
|
||||
emit(const UpdateFailure('APK 下载失败'));
|
||||
}
|
||||
@@ -112,6 +118,97 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 触发系统安装页面
|
||||
Future<void> triggerInstall(String apkPath) async {
|
||||
emit(const UpdateInstalling(isPatch: false));
|
||||
|
||||
try {
|
||||
_logger.i('📦 开始调起系统安装页面');
|
||||
_logger.i('📁 APK 路径: $apkPath');
|
||||
|
||||
// 🔥 验证文件是否存在
|
||||
final file = File(apkPath);
|
||||
if (!await file.exists()) {
|
||||
_logger.e('❌ APK 文件不存在: $apkPath');
|
||||
emit(UpdateFailure('APK 文件不存在,请重新下载'));
|
||||
return;
|
||||
}
|
||||
|
||||
final fileSize = await file.length();
|
||||
_logger.i('📏 APK 文件大小: ${fileSize / 1024 / 1024} MB');
|
||||
|
||||
// 🔥 关键修复:将APK复制到外部存储,避免某些Android版本的安装限制
|
||||
final externalDir = await getExternalStorageDirectory();
|
||||
String finalApkPath = apkPath;
|
||||
|
||||
if (externalDir != null) {
|
||||
final publicApkPath = '${externalDir.path}/app-update-final.apk';
|
||||
_logger.i('📋 复制APK到外部存储: $publicApkPath');
|
||||
|
||||
try {
|
||||
await file.copy(publicApkPath);
|
||||
finalApkPath = publicApkPath;
|
||||
_logger.i('✅ APK复制成功');
|
||||
} catch (e) {
|
||||
_logger.w('⚠️ 复制APK失败,使用原路径: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// 打开 APK 文件,触发系统安装界面
|
||||
_logger.i('🚀 调用 OpenFile.open...');
|
||||
_logger.i('🚀 最终APK路径: $finalApkPath');
|
||||
final result = await OpenFile.open(finalApkPath);
|
||||
_logger.i('📦 安装结果: ${result.message} (type: ${result.type})');
|
||||
|
||||
// 如果用户取消安装,显示提示信息并保留文件路径
|
||||
if (result.type != ResultType.done) {
|
||||
_logger.w('⚠️ 用户取消了安装或安装失败 (type: ${result.type})');
|
||||
|
||||
// 🔥 如果是权限问题,提供更友好的提示
|
||||
String errorMsg = '您取消了安装';
|
||||
if (result.type == ResultType.noAppToOpen) {
|
||||
errorMsg = '没有找到可以安装 APK 的应用,请检查系统设置';
|
||||
} else if (result.type == ResultType.permissionDenied) {
|
||||
errorMsg = '没有安装权限,请在系统设置中允许"安装未知应用"';
|
||||
} else if (result.type == ResultType.error) {
|
||||
errorMsg = '安装出错: ${result.message}';
|
||||
}
|
||||
|
||||
emit(UpdateFailure('$errorMsg,APK 文件位于: $finalApkPath'));
|
||||
} else {
|
||||
// 安装成功,关闭对话框
|
||||
emit(UpdateSuccess());
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.e('❌ 调起安装页面异常: $e');
|
||||
emit(UpdateFailure('调起安装页面失败: $e'));
|
||||
}
|
||||
}
|
||||
|
||||
/// 在浏览器中打开下载链接(手动下载)
|
||||
Future<void> openInBrowser(String apkUrl) async {
|
||||
try {
|
||||
_logger.i('🌐 在浏览器中打开 APK 下载链接');
|
||||
|
||||
final uri = Uri.parse(apkUrl);
|
||||
if (await canLaunchUrl(uri)) {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
_logger.i('✅ 已打开浏览器下载');
|
||||
|
||||
// 🔥 整包更新后,清除补丁版本记录
|
||||
await _versionService.clearPatchVersionInfo();
|
||||
|
||||
emit(UpdateSuccess());
|
||||
} else {
|
||||
_logger.e('❌ 无法打开浏览器');
|
||||
emit(const UpdateFailure('无法打开浏览器'));
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.e('❌ 打开浏览器异常: $e');
|
||||
emit(UpdateFailure('打开浏览器失败: $e'));
|
||||
}
|
||||
}
|
||||
|
||||
/// 取消更新
|
||||
void cancelUpdate() {
|
||||
_logger.i('❌ 用户取消更新');
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'update_cubit.dart';
|
||||
import 'update_state.dart';
|
||||
import 'version_check_service.dart';
|
||||
|
||||
/// 更新对话框
|
||||
/// 更新对话框(带完整流程提示)
|
||||
class UpdateDialog extends StatelessWidget {
|
||||
final AppVersionInfo versionInfo;
|
||||
|
||||
@@ -15,19 +16,28 @@ class UpdateDialog extends StatelessWidget {
|
||||
return BlocListener<UpdateCubit, UpdateState>(
|
||||
listener: (context, state) {
|
||||
if (state is UpdateSuccess) {
|
||||
// 更新成功,关闭对话框
|
||||
Navigator.of(context).pop();
|
||||
|
||||
if (versionInfo.updateType == 'patch') {
|
||||
// 差量更新需要重启
|
||||
_showRestartDialog(context);
|
||||
}
|
||||
// 整包更新会自动打开安装界面,不需要额外操作
|
||||
} else if (state is UpdateFailure) {
|
||||
Navigator.of(context).pop();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('更新失败: ${state.error}')),
|
||||
);
|
||||
|
||||
String errorMessage = state.error;
|
||||
bool showApkPath = false;
|
||||
String? apkPath;
|
||||
|
||||
if (errorMessage.contains('APK 文件位于:')) {
|
||||
final parts = errorMessage.split('APK 文件位于:');
|
||||
if (parts.length > 1) {
|
||||
apkPath = parts[1].trim();
|
||||
showApkPath = true;
|
||||
errorMessage = '您取消了安装';
|
||||
}
|
||||
}
|
||||
|
||||
_showErrorDialog(context, errorMessage, showApkPath: showApkPath, apkPath: apkPath);
|
||||
}
|
||||
},
|
||||
child: AlertDialog(
|
||||
@@ -72,27 +82,64 @@ class UpdateDialog extends StatelessWidget {
|
||||
BlocBuilder<UpdateCubit, UpdateState>(
|
||||
builder: (context, state) {
|
||||
if (state is UpdateDownloading) {
|
||||
return SizedBox(
|
||||
width: 60,
|
||||
height: 60,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
CircularProgressIndicator(
|
||||
value: state.progress,
|
||||
strokeWidth: 3,
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
state.isPatch ? '⬇️ 正在下载补丁...' : '⬇️ 正在下载 APK...',
|
||||
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SizedBox(
|
||||
width: 60,
|
||||
height: 60,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
CircularProgressIndicator(
|
||||
value: state.progress,
|
||||
strokeWidth: 3,
|
||||
),
|
||||
Text('${(state.progress * 100).toInt()}%'),
|
||||
],
|
||||
),
|
||||
Text('${(state.progress * 100).toInt()}%'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
} else if (state is UpdateClearingVersion) {
|
||||
return const Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('✅ 版本号清理完成', style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold)),
|
||||
SizedBox(height: 4),
|
||||
Text('正在调起安装页面...', style: TextStyle(fontSize: 12)),
|
||||
SizedBox(height: 8),
|
||||
CircularProgressIndicator(),
|
||||
],
|
||||
);
|
||||
} else if (state is UpdateReadyToInstall) {
|
||||
return ElevatedButton.icon(
|
||||
onPressed: () {
|
||||
context.read<UpdateCubit>().triggerInstall(state.apkPath);
|
||||
},
|
||||
icon: const Icon(Icons.install_mobile),
|
||||
label: const Text('去安装'),
|
||||
);
|
||||
} else if (state is UpdateInstalling) {
|
||||
return const Text('安装中...');
|
||||
return const Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('📦 正在打开安装页面...', style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold)),
|
||||
SizedBox(height: 4),
|
||||
Text('请在系统安装界面确认安装', style: TextStyle(fontSize: 12)),
|
||||
SizedBox(height: 8),
|
||||
CircularProgressIndicator(),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
return ElevatedButton(
|
||||
onPressed: () {
|
||||
if (versionInfo.updateType == 'patch' && versionInfo.patchUrl != null) {
|
||||
// 差量更新
|
||||
context.read<UpdateCubit>().applyPatch(
|
||||
versionInfo.patchUrl!,
|
||||
versionInfo.version,
|
||||
@@ -100,7 +147,6 @@ class UpdateDialog extends StatelessWidget {
|
||||
md5: versionInfo.patchMd5,
|
||||
);
|
||||
} else if (versionInfo.apkUrl != null) {
|
||||
// 整包更新
|
||||
context.read<UpdateCubit>().downloadAndInstallApk(versionInfo.apkUrl!);
|
||||
}
|
||||
},
|
||||
@@ -129,8 +175,7 @@ class UpdateDialog extends StatelessWidget {
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
Navigator.of(ctx).pop();
|
||||
// TODO: 实现重启逻辑
|
||||
// 可以使用 restart_app 包或退出应用让用户手动打开
|
||||
SystemNavigator.pop();
|
||||
},
|
||||
child: const Text('立即重启'),
|
||||
),
|
||||
@@ -138,4 +183,138 @@ class UpdateDialog extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showErrorDialog(BuildContext context, String message, {bool showApkPath = false, String? apkPath}) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('更新提示'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(message),
|
||||
if (showApkPath && apkPath != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue.shade50,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: Colors.blue.shade200),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'📁 APK 文件位置',
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
apkPath,
|
||||
style: const TextStyle(fontSize: 11, fontFamily: 'monospace'),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
const Text(
|
||||
'您可以到该目录手动点击 APK 文件进行安装',
|
||||
style: TextStyle(fontSize: 11, color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(),
|
||||
child: const Text('确定'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 显示整包更新提示(在浏览器中下载)
|
||||
class FullApkUpdateDialog extends StatelessWidget {
|
||||
final AppVersionInfo versionInfo;
|
||||
|
||||
const FullApkUpdateDialog({super.key, required this.versionInfo});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('发现新版本'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('版本号: ${versionInfo.version}'),
|
||||
const SizedBox(height: 8),
|
||||
const Text('更新类型: 整包更新'),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue.shade50,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: Colors.blue.shade200),
|
||||
),
|
||||
child: const Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'📱 整包更新说明',
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
'• 点击"立即下载"将在浏览器中打开下载链接\n'
|
||||
'• 下载完成后请手动安装 APK\n'
|
||||
'• 安装完成后重启应用即可',
|
||||
style: TextStyle(fontSize: 13, height: 1.5),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (versionInfo.updateDesc.isNotEmpty) ...[
|
||||
const Text('更新内容:', style: TextStyle(fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 4),
|
||||
Text(versionInfo.updateDesc),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
if (!versionInfo.forceUpdate)
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
context.read<UpdateCubit>().cancelUpdate();
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: const Text('稍后'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
if (versionInfo.apkUrl != null) {
|
||||
context.read<UpdateCubit>().downloadAndInstallApk(versionInfo.apkUrl!);
|
||||
Navigator.of(context).pop();
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('正在浏览器中打开下载链接...'),
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
child: const Text('立即下载'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,18 @@ class UpdateDownloading extends UpdateState {
|
||||
const UpdateDownloading(this.progress, {required this.isPatch});
|
||||
}
|
||||
|
||||
/// 清理版本号中
|
||||
class UpdateClearingVersion extends UpdateState {
|
||||
const UpdateClearingVersion();
|
||||
}
|
||||
|
||||
/// 准备安装
|
||||
class UpdateReadyToInstall extends UpdateState {
|
||||
final String apkPath;
|
||||
|
||||
const UpdateReadyToInstall(this.apkPath);
|
||||
}
|
||||
|
||||
/// 安装中
|
||||
class UpdateInstalling extends UpdateState {
|
||||
final bool isPatch;
|
||||
|
||||
@@ -8,7 +8,7 @@ import 'dart:io';
|
||||
class AppVersionInfo {
|
||||
final String version;
|
||||
final int versionCode;
|
||||
final String updateType; // "patch" 或 "full"
|
||||
final String updateType;
|
||||
final bool forceUpdate;
|
||||
final String updateDesc;
|
||||
final String? patchUrl;
|
||||
@@ -29,13 +29,12 @@ class AppVersionInfo {
|
||||
});
|
||||
|
||||
factory AppVersionInfo.fromJson(Map<String, dynamic> json) {
|
||||
// 兼容嵌套结构:如果存在 patch 对象,则从中提取 url 和 md5
|
||||
final patchData = json['patch'] as Map<String, dynamic>?;
|
||||
final fullApkData = json['fullApk'] as Map<String, dynamic>?;
|
||||
|
||||
return AppVersionInfo(
|
||||
version: json['version'] ?? '',
|
||||
versionCode: json['versionCode'] ?? 0, // 处理 null 情况
|
||||
versionCode: json['versionCode'] ?? 0,
|
||||
updateType: json['updateType'] ?? 'full',
|
||||
forceUpdate: json['forceUpdate'] ?? false,
|
||||
updateDesc: json['updateDesc'] ?? '',
|
||||
@@ -59,10 +58,7 @@ class VersionCheckService {
|
||||
receiveTimeout: const Duration(seconds: 10),
|
||||
));
|
||||
|
||||
// 后端接口地址
|
||||
static const String apiUrl = 'http://8.159.134.0:8012/api/update/check';
|
||||
|
||||
// 🔥 补丁版本号文件路径(持久化存储,不会被清理缓存删除)
|
||||
static const String _patchVersionFileName = '.patch_version';
|
||||
|
||||
/// 检查版本更新
|
||||
@@ -74,18 +70,19 @@ class VersionCheckService {
|
||||
_logger.i('🔍 检查版本更新');
|
||||
_logger.i('📱 APK 自带版本: $currentVersion ($currentVersionCode)');
|
||||
|
||||
// 🔥 从文件读取已应用的补丁版本
|
||||
// 从文件读取已应用的补丁版本
|
||||
final patchInfo = await _loadPatchVersionInfo();
|
||||
final appliedPatchVersion = patchInfo['version'] as String?;
|
||||
final appliedPatchVersionCode = patchInfo['versionCode'] as int?;
|
||||
|
||||
_logger.i('📂 读取到的补丁版本: $appliedPatchVersion ($appliedPatchVersionCode)');
|
||||
|
||||
// 如果打过补丁,使用补丁的版本信息;否则使用 APK 自带的版本
|
||||
// 如果打过补丁,使用补丁的版本;否则使用 APK 自带版本
|
||||
final requestVersion = appliedPatchVersion ?? currentVersion;
|
||||
final requestVersionCode = appliedPatchVersionCode ?? currentVersionCode;
|
||||
|
||||
_logger.i('🚀 请求后端版本: $requestVersion ($requestVersionCode)');
|
||||
|
||||
// 调用后端接口
|
||||
final response = await _dio.get(
|
||||
apiUrl,
|
||||
queryParameters: {
|
||||
@@ -104,9 +101,15 @@ class VersionCheckService {
|
||||
|
||||
final versionInfo = AppVersionInfo.fromJson(data);
|
||||
|
||||
// 如果已应用此版本补丁,跳过更新
|
||||
if (appliedPatchVersion == versionInfo.version && versionInfo.updateType == 'patch') {
|
||||
_logger.i('✅ 已应用最新版本补丁: ${versionInfo.version}');
|
||||
// 🔥 关键修复:无论更新类型是什么,只要本地已应用此版本,就跳过
|
||||
if (appliedPatchVersion != null && appliedPatchVersion == versionInfo.version) {
|
||||
_logger.i('✅ 本地已应用版本 ${versionInfo.version},跳过更新(updateType: ${versionInfo.updateType})');
|
||||
return null;
|
||||
}
|
||||
|
||||
// 🔥 额外检查:如果本地补丁版本code >= 服务端返回的versionCode,也跳过
|
||||
if (appliedPatchVersionCode != null && appliedPatchVersionCode >= versionInfo.versionCode) {
|
||||
_logger.i('✅ 本地补丁版本code ($appliedPatchVersionCode) >= 服务端versionCode (${versionInfo.versionCode}),跳过更新');
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -135,8 +138,8 @@ class VersionCheckService {
|
||||
}) async {
|
||||
try {
|
||||
_logger.i('⬇️ 开始下载补丁: $patchUrl');
|
||||
_logger.i('🎯 目标版本: $version ($targetVersionCode)');
|
||||
|
||||
// 1. 手动下载补丁文件
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
final patchPath = '${tempDir.path}/update_patch.so';
|
||||
|
||||
@@ -152,7 +155,6 @@ class VersionCheckService {
|
||||
|
||||
_logger.i('✅ 补丁下载完成,开始应用...');
|
||||
|
||||
// 2. 应用本地补丁文件
|
||||
final result = await FlutterPatcher.applyPatch(
|
||||
PatchInfo(
|
||||
version: version,
|
||||
@@ -163,10 +165,13 @@ class VersionCheckService {
|
||||
);
|
||||
|
||||
if (result.ok) {
|
||||
_logger.i('✅ 补丁应用成功,需要冷启动生效');
|
||||
// 🔥 保存补丁版本号到文件(持久化存储)
|
||||
_logger.i('✅ 补丁应用成功');
|
||||
// 保存补丁版本号到文件
|
||||
await _savePatchVersionInfo(version, targetVersionCode);
|
||||
_logger.i('💾 已保存补丁版本: $version ($targetVersionCode)');
|
||||
|
||||
// 验证保存
|
||||
final verifyInfo = await _loadPatchVersionInfo();
|
||||
_logger.i('💾 已保存并验证: ${verifyInfo['version']} (${verifyInfo['versionCode']})');
|
||||
} else {
|
||||
_logger.e('❌ 补丁应用失败: ${result.error}');
|
||||
}
|
||||
@@ -183,8 +188,10 @@ class VersionCheckService {
|
||||
try {
|
||||
_logger.i('⬇️ 开始下载 APK: $apkUrl');
|
||||
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
final apkPath = '${tempDir.path}/app-update.apk';
|
||||
final cacheDir = await getApplicationCacheDirectory();
|
||||
final apkPath = '${cacheDir.path}/app-update.apk';
|
||||
|
||||
_logger.i('📁 APK 下载路径: $apkPath');
|
||||
|
||||
await _dio.download(
|
||||
apkUrl,
|
||||
@@ -209,13 +216,13 @@ class VersionCheckService {
|
||||
try {
|
||||
_logger.i('🔄 执行回滚操作');
|
||||
await FlutterPatcher.rollback();
|
||||
_logger.i('✅ 回滚成功,下次冷启动生效');
|
||||
_logger.i('✅ 回滚成功');
|
||||
} catch (e) {
|
||||
_logger.e('❌ 回滚失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// 🔥 清除补丁版本信息(整包更新后调用)
|
||||
/// 清除补丁版本信息(整包更新后调用)
|
||||
Future<void> clearPatchVersionInfo() async {
|
||||
try {
|
||||
final directory = await getApplicationSupportDirectory();
|
||||
@@ -229,36 +236,54 @@ class VersionCheckService {
|
||||
}
|
||||
}
|
||||
|
||||
// 🔥 保存补丁版本信息到文件(持久化,不会被清理缓存删除)
|
||||
/// 保存补丁版本信息到文件
|
||||
Future<void> _savePatchVersionInfo(String version, int versionCode) async {
|
||||
try {
|
||||
final directory = await getApplicationSupportDirectory();
|
||||
final file = File('${directory.path}/$_patchVersionFileName');
|
||||
await file.writeAsString('$version|$versionCode');
|
||||
final content = '$version|$versionCode';
|
||||
await file.writeAsString(content);
|
||||
|
||||
// 🔥 立即验证写入
|
||||
final verifyContent = await file.readAsString();
|
||||
_logger.i('💾 补丁版本已保存到: ${file.path}');
|
||||
_logger.i('💾 写入内容: $content');
|
||||
_logger.i('💾 验证读取: $verifyContent');
|
||||
_logger.i('💾 文件存在: ${await file.exists()}');
|
||||
} catch (e) {
|
||||
_logger.e('❌ 保存补丁版本信息失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// 🔥 从文件加载补丁版本信息
|
||||
/// 从文件加载补丁版本信息
|
||||
Future<Map<String, dynamic>> _loadPatchVersionInfo() async {
|
||||
try {
|
||||
final directory = await getApplicationSupportDirectory();
|
||||
final file = File('${directory.path}/$_patchVersionFileName');
|
||||
|
||||
_logger.i('📂 尝试加载补丁版本文件: ${file.path}');
|
||||
_logger.i('📂 文件存在: ${await file.exists()}');
|
||||
|
||||
if (await file.exists()) {
|
||||
final content = await file.readAsString();
|
||||
_logger.i('📂 文件内容: $content');
|
||||
|
||||
final parts = content.split('|');
|
||||
if (parts.length == 2) {
|
||||
final version = parts[0];
|
||||
final versionCode = int.tryParse(parts[1]);
|
||||
if (versionCode != null) {
|
||||
_logger.i('📂 从文件读取补丁版本: $version ($versionCode)');
|
||||
_logger.i('📂 解析成功: version=$version, versionCode=$versionCode');
|
||||
return {'version': version, 'versionCode': versionCode};
|
||||
} else {
|
||||
_logger.e('📂 versionCode 解析失败: ${parts[1]}');
|
||||
}
|
||||
} else {
|
||||
_logger.e('📂 文件格式错误,parts.length=${parts.length}');
|
||||
}
|
||||
}
|
||||
|
||||
_logger.i('📂 未找到有效的补丁版本信息');
|
||||
return {'version': null, 'versionCode': null};
|
||||
} catch (e) {
|
||||
_logger.e('❌ 加载补丁版本信息失败: $e');
|
||||
|
||||
Reference in New Issue
Block a user