Flutter实现从.NET Core API下载APK并自动安装的方法
Flutter实现APK自更新:下载路径配置与安装方案
一、设置正确的APK输出路径
APK需要存放在系统安装器可访问的目录,推荐使用应用外部存储目录(无需额外权限,适配Android 10+沙箱机制),可通过path_provider包获取路径:
添加依赖到
pubspec.yaml:dependencies: path_provider: ^2.1.2获取并使用路径:
import 'package:path_provider/path_provider.dart'; import 'dart:io'; Future<String> getApkSavePath() async { // 获取应用外部存储目录(Android路径示例:/storage/emulated/0/Android/data/[你的包名]/files) Directory? externalDir = await getExternalStorageDirectory(); return '${externalDir!.path}/app_update.apk'; } // 替换原写入代码: String filePath = await getApkSavePath(); File file = await File(filePath).writeAsBytes(response.bodyBytes);
若需将APK存放在公共Download目录,Android 9及以下需额外申请WRITE_EXTERNAL_STORAGE权限,并通过getDownloadsDirectory()获取路径。
二、实现APK安装
1. 配置AndroidManifest.xml权限与适配
在android/app/src/main/AndroidManifest.xml中添加以下配置:
- 安装权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> - Android 10+适配分区存储:
<application ... android:requestLegacyExternalStorage="true"> - Android 11+包可见性(让应用能调用系统安装器):
<queries> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="content" /> <data android:scheme="file" /> <data android:mimeType="application/vnd.android.package-archive" /> </intent> </queries>
2. 调用系统安装器
推荐使用open_file包快速实现安装,步骤如下:
添加依赖:
dependencies: open_file: ^3.3.2编写安装方法:
import 'package:open_file/open_file.dart'; Future<void> installApk(String filePath) async { var result = await OpenFile.open( filePath, type: 'application/vnd.android.package-archive', ); if (result.type != ResultType.done) { // 处理安装失败场景(如权限不足、文件损坏) print('安装失败:${result.message}'); } } // 下载完成后调用: await installApk(filePath);
额外提示
- 下载后建议校验APK文件的MD5/SHA值,避免文件损坏导致安装失败;
- 下载过程中可添加进度条提示,提升用户体验;
- 需处理用户拒绝安装权限的情况,引导用户前往设置开启权限。
内容的提问来源于stack exchange,提问作者aoiTenshi
相关产品推荐
相关产品推荐

