import 'dart:io'; import 'package:dio/dio.dart'; import 'package:install_plugin/install_plugin.dart'; import 'package:lszlgl/config/app_config.dart'; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; import '../main.dart'; import '../network/my_api.dart'; import '../router/my_navigator.dart'; import '../widget/upgrade_dialog.dart'; class UpgradeService { UpgradeService._(); static Future download(String apkUrl, String apkName, ProgressCallback progress) async { String savePath = '${await getApkDirectoryPath()}/$apkName'; var rsp = await Dio().download( apkUrl, savePath, onReceiveProgress: (count, total) { if (total < 0) return; progress.call(count, total); }, ); return rsp; } /// 获取apk文件夹路径 static Future getApkDirectoryPath() async { return '${(await getApplicationSupportDirectory()).path}/apk'; } /// 获取apk文件 static Future getApkFile(String apkName) async { return File('${await getApkDirectoryPath()}/$apkName'); } /// 安装APK static Future installApk(String path) async { var status = await Permission.requestInstallPackages.status; if (!status.isGranted) { Permission.requestInstallPackages.request(); return false; } await InstallPlugin.install(path); return true; } /// 从路径中获取文件名 static String getName(String path) { var pathSplit = path.split('/'); return pathSplit[pathSplit.length - 1]; } static bool checking = false; /// 检查版本更新 static Future checkUpgrade(bool showLoading) async { if (!Platform.isAndroid) return; if (checking) return; checking = true; if (showLoading) MyNavigator.showLoading(msg: '正在获取版本更新'); try { // 获取apk下载地址 var path = (await MyApi.get().getAppDownloadUrl()).data; if (showLoading) MyNavigator.dismissLoading(); if (path != null) { // 获取线上版本 lszlgl_release_0.0.2_2.apk List nameSplit = UpgradeService.getName(path).split('_'); int onlineCode = int.parse(nameSplit[nameSplit.length - 1].split('.').first); int localCode = int.parse(AppConfig.packageInfo.buildNumber); logger.d('versionUpgrade:localCode:$localCode onlineCode:$onlineCode'); if (localCode >= onlineCode) { if (showLoading) MyNavigator.showToast('已是最新版本'); } else { // 版本更新 UpgradeDialog.showDialog(path); } } } catch (e) { logger.e(e); if (showLoading) MyNavigator.dismissLoading(); } checking = false; } }