Flutter实现android应用内版本更新功能

#插件
1.package_info:获取应用版本信息
2.flutter_downloader :从服务器下载apk文件
配置:

provider
     android:name="androidx.work.impl.WorkManagerInitializer"
     android:authorities="${applicationId}.workmanager-init"
     android:enabled="false"
     android:exported="false" />

 
     
     
 

添加安装文件权限



 
 

3.open_file:打开下载的apk文件,并自动安装
#代码
##获取应用版本信息

PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      var currentVersionCode = packageInfo.buildNumber;
      print("version:" + currentVersionCode + ",net:" + _serviceVersionCode);
      //_serviceVersionCode为从服务器获取的升级最新的版本号
      if (int.parse(_serviceVersionCode) > int.parse(currentVersionCode)) {
        _showNewVersionAppDialog(packageInfo); //弹出“版本更新”的对话框
      }
    });

##下载apk文件
先对FlutterDownloader进行初始化

WidgetsFlutterBinding.ensureInitialized();
await FlutterDownloader.initialize();

创建下载任务
先获取安装地址

 Future _apkLocalPath() async {
    final directory = await getExternalStorageDirectory();
    _localPath = directory.path.toString();
    return _localPath;
  }

创建存储文件

final path = (await _apkLocalPath()) + '/Download';
    final saveDir = Directory(path);
    bool hasExisted = await saveDir.exists();
    if (!hasExisted) {
      saveDir.create();
    }

下载

 //下载
    final tastId = await FlutterDownloader.enqueue(
        url: downloadUrl,
        fileName: "apkname.apk",
        savedDir: path,
        showNotification: true,
        openFileFromNotification: true);

下载监听

 FlutterDownloader.registerCallback(downloadCallback);
 static void downloadCallback(
      String id, DownloadTaskStatus status, int progress) {
    //当下载完成时,调用安装
    String dir;
    if (status == DownloadTaskStatus.complete) {
      FlutterDownloader.initialize().then((onValue){
        FlutterDownloader.loadTasks().then((onValue){
          DownloadTask downloadTask = onValue[0];
          dir = downloadTask.savedDir;
          OpenFile.open(dir);
          FlutterDownloader.open(taskId: id);
        });
      });



    }
  }

你可能感兴趣的:(android,flutter)