提供两种方法
1.Dio下载升级
import 'package:permission_handler/permission_handler.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:open_file/open_file.dart';
/// 下载安卓更新包
Future<String> downloadAndroid(String url) async {
final permissions = await Permission.storage.status;
print('permission $permissions');
if (!permissions.isGranted) {
final permission = await Permission.storage.request();
print('permission $permission');
} else {
print('permission granted');
}
startDownLoad(url);
}
///开始下载
startDownLoad(String url) async{
/// 创建存储文件
print(url);
Directory storageDir = await getTemporaryDirectory();
String storagePath = storageDir.path;
final path = storagePath + '/xxx.apk';
try {
var dio = Dio();
//配置dio代理 方便debug
// (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
// client.badCertificateCallback =
// (X509Certificate cert, String host, int port) {
// return Platform.isAndroid;
// };
// client.findProxy = (uri) {
// return "PROXY 192.168.0.154:8888";
// };
// };
final Response response = await dio.download(url, path, onReceiveProgress: (int count, int total) {
if (total == -1) {
progressValue = 0.01;
} else {
progressValue = count / total.toDouble();
}
print('progress: $progressValue');
setState(() {});
if (progressValue == 1) {
//下载完成,跳转到程序安装界面
openApk(path);
}
});
print(response.data);
} catch (e) {
print('$e');
progressValue = 0;
}
}
//打开apk 开始安装
openApk(String path) async {
final openResult = await OpenFile.open(path);
print('openResult:${openResult.type}');
if (openResult.type == ResultType.error) {
} else if (openResult.type == ResultType.permissionDenied) {
} else if (openResult.type == ResultType.fileNotFound) {
} else if (openResult.type == ResultType.noAppToOpen) {
} else {
if (widget.forceUpdate) Navigator.pop(context);
print('open result done');
}
}
2.使用ota库升级
ota_update
try {
//LINK CONTAINS APK OF FLUTTER HELLO WORLD FROM FLUTTER SDK EXAMPLES
OtaUpdate()
.execute(
widget.loadingUrl,
// OPTIONAL
destinationFilename: 'xxx.apk',
//OPTIONAL, ANDROID ONLY - ABILITY TO VALIDATE CHECKSUM OF FILE:
// sha256checksum: "********************",
).listen(
(OtaEvent event) {
print(event.status);
print(event.value);
setState(() {
progressValue = stringToInt(event.value)/100;
});
},
);
} catch (e) {
print('Failed to make OTA update. Details: $e');
}
网友评论