Flutter 项目 app迭代更新

Flutter 项目 app迭代更新_第1张图片
大概思路,能进入这个帖子基本也都知道:
1.获取当前版本是否为低版本(略)
2.更新

方法一:

直接使用url_launcher:跳转本地浏览器下载
需要依赖url_launcher,版本号没有要求

url_launcher: ^5.0.2

currUrl:为下载地址

 _UpdateURL() async {
    if (await canLaunch(currUrl)) {
      await launch(currUrl);
    } else {
      throw 'Could not launch $currUrl';
    }
  }

方法二:

使用到的库,pubspec .yaml配置
分别是下载文件,获取路径,权限,打开文件

  flutter_downloader: ^1.1.7
  path_provider: ^1.1.0
  permission_handler: ^3.0.0
  open_file: ^2.0.1+2

Android manifest.xml配置

flutter_downloader:https://pub.dev/packages/flutter_downloader
⚠️:IOSIOS配置会有不同
Flutter 项目 app迭代更新_第2张图片

 <provider
            android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
            android:authorities="${applicationId}.flutter_downloader.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

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

        <provider
            android:name="vn.hunghd.flutterdownloader.FlutterDownloaderInitializer"
            android:authorities="${applicationId}.flutter-downloader-init"
            android:exported="false">
            <meta-data
                android:name="vn.hunghd.flutterdownloader.MAX_CONCURRENT_TASKS"
                android:value="5" />
        </provider>

查看是否有权限

// 检查权限
  Future<bool> _checkPermission() async {
    if (Theme.of(context).platform == TargetPlatform.android) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission != PermissionStatus.granted) {
        Map<PermissionGroup, PermissionStatus> permissions =
            await PermissionHandler()
                .requestPermissions([PermissionGroup.storage]);
        if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

下载apk

把apk放在某位置,进行请求下载

  void _requestDownload() async {
    final path = await _apkLocalPath;
    final taskId = await FlutterDownloader.enqueue(
      url: 'https://github.com/alibaba/flutter-go/raw/master/FlutterGo.apk',
      savedDir: path,
      showNotification: true,
      // show download progress in status bar (for Android)
      openFileFromNotification:
          true, // click on notification to open downloaded file (for Android)
    );
  }

监听下载进度

⚠️这里写在initState()方法中

 FlutterDownloader.registerCallback((id, status, progress) async {
      setState(() {
        _currProgress = progress;
      });
      print(
          "id:${id}===== status=======:${status}=====progress======:${progress}");
      // 当下载完成时,调用安装
      if (status == DownloadTaskStatus.complete) {
        OpenFile.open(_localPath);
        FlutterDownloader.open(taskId: id);
      }
    });

ok 重点基本就到这里了,真机测

附上全部代码测试:

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_go/blocs/bak/search_api.dart';
import 'dart:convert';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:open_file/open_file.dart';
import 'package:url_launcher/url_launcher.dart';

class UpdatePage extends StatefulWidget {
  @override
  _UpdatePageState createState() => _UpdatePageState();
}

class _UpdatePageState extends State<UpdatePage> {
  static const currUrl =
      'https://github.com/alibaba/flutter-go/raw/master/FlutterGo.apk';

  @override
  void initState() {
    super.initState();
    FlutterDownloader.registerCallback((id, status, progress) async {
      setState(() {
        _currProgress = progress;
      });
      print(
          "id:${id}===== status=======:${status}=====progress======:${progress}");
      // 当下载完成时,调用安装
      if (status == DownloadTaskStatus.complete) {
        OpenFile.open(_localPath);
        FlutterDownloader.open(taskId: id);
      }
    });
    _permissisonReady = false;
    _prepare();
  }

  bool _isLoading;
  bool _permissisonReady;
  String _localPath;
  int _currProgress = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 20),
          width: double.infinity,
          height: 10.0,
          child: new LinearProgressIndicator(
            value: _currProgress / 100,
            backgroundColor: Colors.red,
          ),
        ),
        Center(
          child: Text("现在是1.0.0",
              textAlign: TextAlign.center, style: TextStyle(fontSize: 20)),
        ),
        Center(
          child: FlatButton(
            onPressed: () {
              print("点击${_permissisonReady}");
              if (_permissisonReady) {
                _requestDownload();
              } else {
                _checkPermission().then((hasGranted) {
                  setState(() {
                    _permissisonReady = hasGranted;
                  });
                });
              }
            },
            child: Text(
              "点击获取新版本",
              style: TextStyle(color: Colors.white),
            ),
            color: Colors.red[800],
          ),
        ),
        Center(
          child: FlatButton(
            onPressed: () {
              print("local===: _UpdateURL");
              _UpdateURL();
            },
            child: Text(
              "更新版本",
              style: TextStyle(color: Colors.white),
            ),
            color: Colors.red[800],
          ),
        ),
      ],
    );
  }

  _UpdateURL() async {
    if (await canLaunch(currUrl)) {
      await launch(currUrl);
    } else {
      throw 'Could not launch $currUrl';
    }
  }

  Future<Null> _prepare() async {
    _permissisonReady = await _checkPermission();
  }

  //检查权限
  Future<bool> _checkPermission() async {
    if (Theme.of(context).platform == TargetPlatform.android) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission != PermissionStatus.granted) {
        Map<PermissionGroup, PermissionStatus> permissions =
            await PermissionHandler()
                .requestPermissions([PermissionGroup.storage]);
        if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  void _requestDownload() async {
    final path = await _apkLocalPath;
    final taskId = await FlutterDownloader.enqueue(
      url: currUrl,
      fileName: "new_FlutterGo.apk",
      savedDir: path,
      showNotification: true,
      // show download progress in status bar (for Android)
      openFileFromNotification:
          true, // click on notification to open downloaded file (for Android)
    );
  }

  // 获取安装地址
  Future<String> get _apkLocalPath async {
//    final directory = widget.platform == TargetPlatform.android
//        ? await getExternalStorageDirectory()
//        : await getApplicationDocumentsDirectory();

    final directory = await getExternalStorageDirectory();
    _localPath = directory.path.toString();
    return _localPath;
  }
}


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