[Flutter] 检测新版本功能实现

检测新版本

配置权限

配置AndroidMenifest.xml文件

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

流程图

开始检测

//开始检测按钮
ElevatedButton(
    onPressed: () {
        //__getPackageInfo()返回值是Future,用then拆开获得当前版本号
        _getPackageInfo().then((value) {
            //当前版本号赋值给version,最新版本号暂设置在全局newVersion
            version = value;
            //引用CheckVersion类比较当前版本号和最新版本号大小
            CheckVersion.isNewVersion(version, newVersion)
                ? _needUpdate()//需要更新
                : _needNotUpdate();//不需要更新
        });
    },
    child: Text('检测新版本'),
),
//返回当前版本号
_getPackageInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version;
    return version;
}

是否需要更新

//需要更新Dialog
void _needUpdate() async {
    await showDialog(
        context: context,
        builder: (context) {
            return AlertDialog(
                title: Text("版本检测!"),
                content: Text("发现新的版本,是否更新!"),
                actions: <Widget>[
                    TextButton(
                        child: Text("否"),
                        onPressed: () {
                            Navigator.pop(context);
                        },
                    ),
                    TextButton(
                        child: Text("是"),
                        onPressed: () {
                            _downLoad();//引用下载方法
                            Navigator.pop(context);//取消dialog
                        })
                ],
            );
        });
}
//不需要更新Dialog
_needNotUpdate() async {
    await showDialog(
        context: context,
        builder: (context) {
            return AlertDialog(
                title: Text('版本检测'),
                content: Text('无需更新,已是最新版本!'),
                actions: [
                    TextButton(
                        child: Text("好"),
                        onPressed: () {
                            Navigator.pop(context, 'Cancle');//取消dialog
                        },
                    ),
                ],
            );
        });
}

开始执行下载方法

 //下载打开文件
  _downLoad() async {
    var permission = await this._checkPermission();//检测是否有权限
      //如果有权限,配置安装路径
    if (permission) {
      Directory? directory = await getExternalStorageDirectory();
      String? _localPath;
      //注意Flutter2.2以后的版本加入了Null safety
      if (directory != null) {
        _localPath = directory.path;
        String _appName = "app-release.apk";
        String _savePath = "$_localPath/$_appName";
        String apkUrl = "https://www.tobutomi.top/app/app-release.apk";
         //实例化Dio网络请求库
        Dio dio = new Dio();
          //实例化下载进度Dialog库
        ProgressDialog pd = ProgressDialog(context: context);
        pd.show(max: 100, msg: '正在下载...');
          //使用dio.download进行下载
        await dio.download(apkUrl, _savePath,
            onReceiveProgress: (received, total) {
         //下载进度
          int progress = (((received / total) * 100).toInt());
          pd.update(value: progress);
        });
        await OpenFile.open(_savePath,
            type: "application/vnd.android.package-archive");
      } else {
        print("获取目录失败");
      }
    } else {
      print("没有权限");
    }
  }
//检查权限_checkPermission
Future<bool> _checkPermission() async {
    if (Theme.of(context).platform == TargetPlatform.android) {
        final status = await Permission.storage.status;
        if (status != PermissionStatus.granted) {
            final result = await Permission.storage.request();
            if (result == PermissionStatus.granted) {
                return true;
            }
        } else {
            return true;
        }
    }
    return false;
}

完整代码

CheckVersion工具类

class CheckVersion {
    static bool isNew = false;
    static isNewVersion(version, newversion) {
        List verList = version.split('.');
        List newVerList = newversion.split('.');
        if (int.parse(newVerList[0]) > int.parse(verList[0])) {
            isNew = true;
        } else if (int.parse(newVerList[0]) == int.parse(verList[0])) {
            if (int.parse(newVerList[1]) > int.parse(verList[1])) {
                isNew = true;
            } else if (int.parse(newVerList[1]) == int.parse(verList[1])) {
                if (int.parse(newVerList[2]) > int.parse(verList[2])) {
                    isNew = true;
                }
            }
        }
        return isNew;
    }
}

主页代码

import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:open_file/open_file.dart';
import 'package:dio/dio.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../components/CheckVersion.dart';
import 'package:sn_progress_dialog/sn_progress_dialog.dart';

class AppVersionPage extends StatefulWidget {
    AppVersionPage({Key? key}) : super(key: key);
    _AppVersionPageState createState() => _AppVersionPageState();
}

class _AppVersionPageState extends State<AppVersionPage> {
    //设置新版本号,可以存于云端
    var newVersion = '1.0.0';
    var version;
    //需要更新
    void _needUpdate() async {
        await showDialog(
            context: context,
            builder: (context) {
                return AlertDialog(
                    title: Text("版本检测!"),
                    content: Text("发现新的版本,是否更新!"),
                    actions: <Widget>[
                        TextButton(
                            child: Text("否"),
                            onPressed: () {
                                Navigator.pop(context);
                            },
                        ),
                        TextButton(
                            child: Text("是"),
                            onPressed: () {
                                _downLoad();
                                Navigator.pop(context);
                            })
                    ],
                );
            });
    }

    //不需要更新
    _needNotUpdate() async {
        await showDialog(
            context: context,
            builder: (context) {
                return AlertDialog(
                    title: Text('版本检测'),
                    content: Text('无需更新,已是最新版本!'),
                    actions: [
                        TextButton(
                            child: Text("好"),
                            onPressed: () {
                                Navigator.pop(context, 'Cancle');
                            },
                        ),
                    ],
                );
            });
    }

    //获取版本号
    _getPackageInfo() async {
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        String version = packageInfo.version;
        return version;
    }

    //检查权限
    Future<bool> _checkPermission() async {
        if (Theme.of(context).platform == TargetPlatform.android) {
            final status = await Permission.storage.status;
            if (status != PermissionStatus.granted) {
                final result = await Permission.storage.request();
                if (result == PermissionStatus.granted) {
                    return true;
                }
            } else {
                return true;
            }
        }
        return false;
    }

    //下载打开文件
    _downLoad() async {
        var permission = await this._checkPermission();

        if (permission) {
            Directory? directory = await getExternalStorageDirectory();
            String? _localPath;
            //注意Flutter2.2以后的版本加入了Null safety
            if (directory != null) {
                _localPath = directory.path;
                String _appName = "aaa.apk";
                String _savePath = "$_localPath/$_appName";
                String apkUrl = "https://www.tobutomi.top/app/app-release.apk";

                Dio dio = new Dio();
                ProgressDialog pd = ProgressDialog(context: context);
                pd.show(max: 100, msg: '正在下载...');
                await dio.download(apkUrl, _savePath,
                                   onReceiveProgress: (received, total) {
                                       int progress = (((received / total) * 100).toInt());
                                       pd.update(value: progress);
                                   });
                await OpenFile.open(_savePath,
                                    type: "application/vnd.android.package-archive");
            } else {
                print("获取目录失败");
            }
        } else {
            print("没有权限");
        }
    }

    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
                title: Text("app升级演示"),
            ),
            body: Center(
                child: ElevatedButton(
                    onPressed: () {
                        _getPackageInfo().then((value) {
                            version = value;
                            CheckVersion.isNewVersion(version, newVersion)
                                ? _needUpdate()
                                : _needNotUpdate();
                        });
                    },
                    child: Text('检测新版本'),
                ),
            ),
        );
    }
}

posted @ 2022-02-20 20:41  漫游者杰特  阅读(359)  评论(0编辑  收藏  举报