flutter 應用自動更新


話不多說直接上代碼:

package_info: ^0.4.0+16
  path_provider: ^1.6.5
  open_file: ^3.0.1
  url_launcher: ^5.4.2
_update() async {
    if (Platform.isIOS) {
//      String url =
//          'itms-apps://itunes.apple.com/cn/app/id414478124?mt=8'; // 這是微信的地址,到時候換成自己的應用的地址
//      if (await canLaunch(url)) {
//        await launch(url);
//      } else {
//        throw 'Could not launch $url';
//      }
    } else if (Platform.isAndroid) {
      String url = HttpUtils.VERSION_URL + 'app-release.apk';
      try {
        /// 創建存儲文件
        Directory storageDir = await getExternalStorageDirectory();
        String storagePath = storageDir.path;
        File _apkFile = await downloadAndroid(storagePath,url);
        OpenFile.open("${storagePath}/app-release.apk");
      } catch (e) {
        print('${e}');
      }
    }
  }

  /// 下載安卓更新包
  Future<File> downloadAndroid(String storagePath,String url) async {
    File file = new File('$storagePath/app-release.apk');
    if (!file.existsSync()) {
      file.createSync();
    }
    try {
      print("-------------333333333333");
      Function tr = throttle((List args){
        print("-----------------------6666");
        int count = args[0];
        int total = args[1];
        double radio = count/total;
        String str = (_progress_val*100).toInt().toString();
        setState(() {
          _progress_val = radio;
          _progress = "下載進度:${str}%";
        });
      }, 500);
      /// 發起下載請求
      Response response = await Dio().get(url,
          onReceiveProgress: (int count,int total){
//            tr([count,total]);
            double radio = count/total;
            String str = (_progress_val*100).toInt().toString();
            setState(() {
              _progress_val = radio;
              _progress = "下載進度:${str}%";
            });
          },
          options: Options(
            responseType: ResponseType.bytes,
            followRedirects: false,
          ));
      file.writeAsBytesSync(response.data);
      return file;
    } catch (e) {
      print(e);
    }
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM