jjsos_autosos_flutter/lib/service/update_service.dart

65 lines
1.9 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import 'dart:io';
import 'package:autosos_flutter/api/user_api.dart';
import 'package:autosos_flutter/config/constant.dart';
import 'package:autosos_flutter/model/misc.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';
/// 应用内更新服务(对应 Android HttpUpdateVersion
class UpdateService {
static final UpdateService instance = UpdateService._();
UpdateService._();
final _dio = Dio();
/// 检查更新
Future<AppUpdate?> checkUpdate() async {
try {
final resp = await UserApi.instance.checkUpdate();
if (!resp.isSuccess) return null;
final update = resp.data!;
Constant.NECUPDATE = update.forceUpdate ? 3 : 2;
return update;
} catch (e) {
debugPrint('checkUpdate failed: $e');
Constant.NECUPDATE = 5;
return null;
}
}
/// 下载并安装
Future<void> downloadAndInstall(AppUpdate update) async {
if (update.downloadUrl == null) {
EasyLoading.showError('下载链接为空');
return;
}
EasyLoading.showProgress(0, status: '下载中 0%');
final dir = await getTemporaryDirectory();
final apkPath = '${dir.path}/autosos_${update.latestVersion}.apk';
await _dio.download(
update.downloadUrl!,
apkPath,
onReceiveProgress: (received, total) {
if (total > 0) {
final p = received / total;
EasyLoading.showProgress(p, status: '下载中 ${(p * 100).toStringAsFixed(0)}%');
}
},
);
EasyLoading.dismiss();
if (Platform.isAndroid) {
await InstallPlugin.install(apkPath);
} else if (Platform.isIOS) {
await OpenFilex.open(apkPath);
}
}
}