flutter开发实战-应用更新apk下载、安装apk、启动应用实现

这篇具有很好参考价值的文章主要介绍了flutter开发实战-应用更新apk下载、安装apk、启动应用实现。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

flutter开发实战-应用更新apk下载、安装apk、启动应用实现

在开发过程中,经常遇到需要更新下载新版本的apk文件,之后进行应用更新apk下载、安装apk、启动应用。我们在flutter工程中实现下载apk,判断当前版本与需要更新安装的版本进行比对判断,通过判断VersionCode来确定下载新版版APK

一、应用更新apk下载

当应用需要更新的时候,我们需要判断版本号,在flutter工程中versionCode是工程中的pubspec.yaml中的version确定的。

如version: 1.0.0+1

version为1.0.0,versionCode为1

需要我们获取接口,需要判断的就是versionCode确定是否需要下载apk。

1.1、获取新版本地址接口

获取新版本的接口使用的是Dio库。dio 是一个强大的 Dart HTTP 请求库,支持全局配置、Restful API、FormData、拦截器、 请求取消、Cookie 管理、文件上传/下载、超时以及自定义适配器等。

这里的请求为GET请求,

Response? response = await dio.get(requestUrl,
                  queryParameters: params,
                  options: Options(contentType: Headers.jsonContentType));

我这里就不写请求的逻辑了。
根据请求,获取到了

// 获取检查版本

Future<void> checkVersion() async {
    var params = {};

    ApiRepository.checkVersion(
        params: params,
        success: (response) {
          // {"version":"2","url":"http://wwww.laileshuo.com/download/myapp_v1.0.0_release.apk"}
          var object = response.object;
          if (object != null && (object is Map) && object.isNotEmpty) {
            String? versionCode = object['versionCode'];
            String? url = object['url'];
            // 判断是否需要下载更新
            String versionCodeStr = "";
            if (version != null) {
              versionCodeStr = "${versionCode}";
            }
            checkAppVersionUpdate(versionCodeStr: versionCodeStr, apkUrl: url);
          }
          print(
              "checkVersion params:${params}, object:${object.toString()}");
        },
        failure: (error) {
          print(
              "checkVersion params:${params}, error:${error.toString()}");
        });
  }

通过检查新版本接口获取到了url及versionCode,这里的versionCode和pubspec.yaml的进行比较看是否需要下载apk。

判断下载apk

Future<void> checkAppVersionUpdate({String? versionCodeStr, String? apkUrl}) async {
    try {
      if (versionCodeStr != null &&
          apkUrl != null &&
          versionCodeStr.isNotEmpty &&
          apkUrl.isNotEmpty) {
        String curVersionCodeStr = await PlatformUtils.getBuildNum();
        int versionCode = int.parse(versionCodeStr);
        int curVersionCode = int.parse(curVersionCodeStr);
        if (versionCode > curVersionCode) {
          // 需要更新的版本code,大于当前的版本才更新
          
        }
      }
    } catch (e) {
      print(
          "appVersionUpdate apkUrl:${apkUrl}, version:${version}, exception:${e.toString()}");
    }
  }

1.2、下载Apk

在判断需要更新的时候,我们需要下载新版本的apk。下载的库我们使用的也是Dio。

下载的代码可参考https://blog.csdn.net/gloryFlow/article/details/131658621

当获取到新版的下载地址url时候,需要下载apk

void downApk(String url, String saveDestPath) {
	HttpApi().doDownload(url, saveDestPath, cancelToken: CancelToken(),
        progress: (int received, int total) {
      // 下载进度
      setState(() {
        _downloadRatio = (received / total);
        if (_downloadRatio == 1) {
          _downloading = false;
        }
        _downloadIndicator = (_downloadRatio * 100).toStringAsFixed(2) + '%';
      });
    }, completion: () {
      // 下载成功
      FlutterLoadingHud.showToast(message: "\"下载完成\"");
    }, failure: (error) {
      // 下载出错
      FlutterLoadingHud.showToast(message: error.message);
    });
}

下载完成后可以执行安装并且启动操作了。

二、APK安装及启动

APK安装及启动需要原生插件来实现。

2.1、创建原生插件flutter_package_manager

创建flutter plugin,我使用的工具是Android studio。

配置如下内容:

  • Project name
  • Project location
  • Description
  • Project type: Plugin
  • Android language
  • iOS language
  • Platforms

如图所示

flutter apk 下载更新,移动开发,flutter开发实战,flutter,flutter,apk下载,apk安装,apk启动,dio,静默安装,Android

我们需要实现installThenStart

/// An implementation of [FlutterPackageManagerPlatform] that uses method channels.
class MethodChannelFlutterPackageManager extends FlutterPackageManagerPlatform {
  /// The method channel used to interact with the native platform.
  
  final methodChannel = const MethodChannel('flutter_package_manager');

  
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  
  Future<void> installThenStart(String apkFilePath, String activity) async {
    final result = await methodChannel.invokeMethod<void>('installThenStart');
    return result;
  }
}

可以看到定义了installThenStart,需要apkFilePath与activity作为参数。

在Android端实现,由于我这边需要静默安装(apk在后台安装,不出现安装界面的提示)

public class FlutterPackageManager implements MethodCallHandler {
    private static final String TAG = "FlutterPackageManager";

    private final Registrar registrar;

    /**
     * Plugin registration.
     */
    public static void registerWith(Registrar registrar) {
        final MethodChannel channel = new MethodChannel(registrar.messenger(), "flutter_package_manager");
        channel.setMethodCallHandler(new FlutterPackageManager(registrar));
    }

    private FlutterPackageManager(Registrar registrar) {
        this.registrar = registrar;
    }

    
    public void onMethodCall(MethodCall call, Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success(android.os.Build.VERSION.RELEASE);
        } else if (call.method.equals("installThenStart")) {
            String path = call.arguments['filePath'];
	    String activity = call.arguments['activity'];
	    installApk(path, activity);
        } else {
            result.notImplemented();
        }
    }

    void installApk(String path, String activity) {
    	// root权限静默安装实现 实现实际使用的是su pm install -r filePath命令。
	Process process = null; 
   	OutputStream out = null; 
   	InputStream in = null; 
   	try { 
   		// 请求root 
   		process = Runtime.getRuntime().exec("su"); 
   		out = process.getOutputStream(); 
   		// 调用安装 
   		out.write(("pm install -r " + path + "\n").getBytes()); 
   		in = process.getInputStream(); 
   		int len = 0; 
   		byte[] bs = new byte[256]; 
   		while (-1 != (len = in.read(bs))) { 
   		String state = new String(bs, 0, len); 
   		if (state.equals("Success\n")) { 
    			//安装成功后的操作 
			startActivity(activity);
     		} 
    	   } 
   	} catch (IOException e) { 
    		e.printStackTrace(); 
   	} catch (Exception e) { 
    		e.printStackTrace(); 
   	} finally { 
    		try { 
     			if (out != null) { 
      				out.flush(); 
      				out.close(); 
     			} 
     			if (in != null) { 
      				in.close(); 
     			} 
    		} catch (IOException e) { 
     			e.printStackTrace(); 
    		} 
   	} 
 
    }

    void startActivity(String activity) {
        // activity格式为'com.laileshuo.app/com.laileshuo.app.MainActivity'
    	Intent mIntent = new Intent(); 
	val componentName = ComponentName(this, activity)
	val intent = Intent().setComponent(componentName)
	startActivity(intent)
    }
}

当然,工程中的AndroidManifest.xml也需要做相应的调整,如下

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.laileshuo.app">
   <application
        tools:replace="android:label"
        android:label="我的应用"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name="com.laileshuo.app.MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

2.2、如果非root环境安装,可以使用open_file插件

需要在pubspec.yaml引入插件

dependencies:
  open_file: ^3.3.2

在可以直接使用代码安装apk

import 'package:open_file/open_file.dart';

OpenFile.open(apkFilePath);

当与关于FileProvider的其他插件发生冲突时,需要配置AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="xxx.xxx.xxxxx">
    <application>
        ...
        <provider
                android:name="androidx.core.content.FileProvider"
                android:authorities="${applicationId}.fileProvider"
                android:exported="false"
                android:grantUriPermissions="true"
                tools:replace="android:authorities">
            <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/filepaths"
                    tools:replace="android:resource" />
        </provider>
    </application>
</manifest>

三、小结

flutter开发实战-应用更新apk下载、安装apk、启动应用实现。在开发过程中,经常遇到需要更新下载新版本的apk文件,之后进行应用更新apk下载、安装apk、启动应用。我们在flutter工程中实现下载apk,判断当前版本与需要更新安装的版本进行比对判断,通过判断VersionCode来确定下载新版版APK。内容较多,描述可能不准确,请见谅。

https://blog.csdn.net/gloryFlow/article/details/133440529

学习记录,每天不停进步。文章来源地址https://www.toymoban.com/news/detail-783567.html

到了这里,关于flutter开发实战-应用更新apk下载、安装apk、启动应用实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • flutter创建、安装扩展包、打包apk

    要在VSCode中创建一个Flutter应用程序,请按照以下步骤进行操作: 安装Flutter SDK:请确保你已经安装了Flutter SDK,并配置了Flutter的环境。你可以在Flutter的官方网站上找到安装和设置Flutter的详细说明。 安装VSCode插件:打开VSCode,并安装以下插件: Flutter:提供了用于开发Flutte

    2024年02月09日
    浏览(32)
  • PIco4发布使用UNITY开发的Vr应用,格式为apk,安装的时候发生解析错误

    参考链接 : adb install APK报错Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI]_调用者不被允许测试的测试程序_小龙在山东的博客-CSDN博客 Pico Developer Answers 完成项目配置 - PICO 开发者平台 如何将apk、obb文件打包至pico设备中 - 掘金 Requires newer sdk version #30 (current version is #28) · Issue #633

    2024年02月04日
    浏览(47)
  • flutter开发实战-build编译macos环境可安装dmg

    flutter开发实战-build编译macos环境可安装dmg 之前开发中需要变异Macos成dmg的需求,这里记录一下build编译macos环境可安装dmg的过程。 目录如下 如果工程没有macos,需要增加macos支持的平台。命令 运行macos无法访问http请求 可以在macos目录runner文件夹中 DebugProfile.entitlements和 Release

    2024年02月16日
    浏览(33)
  • 给APK签名—两种方式(flutter android 安装包)

    前提:给未签名的apk签名,可以先检查下apk有没有签名 通过命令行查看:打开终端或命令行界面,导入包含APK文件的目录,并执行以下命令: 将 your_app.apk 替换为要检查的APK文件名。执行命令后,你将看到与APK文件关联的签名信息。 注意:上述命令基于Java Development Kit (JDK

    2024年02月16日
    浏览(33)
  • uniapp:实现手机端APP登录强制更新,从本地服务器下载新的apk更新,并使用WebSocket,实时强制在线用户更新

    实现登录即更新,或实时监听更新 本文介绍的是在 App打开启动 的时候调用更新,点击下方链接,查看使用 WebSocket 实现 实时 通知 在线用户 更新。 uniapp:全局消息是推送,实现app在线更新,WebSocket,apk上传: 背景 :内部手持机app开发功能,需要更新的到车间各个手持机上。

    2024年02月03日
    浏览(28)
  • Flutter移动应用开发 - 01 Flutter初次安装、模拟器配置教程(手把手版)

    首先先安装一个编辑器,这边选用的是Android Studio(Android Studio)。Android Studio的下载和项目创建平平无奇,唯一可能有问题的就是gradle文件的下载,如果没翻墙的话需要手动下载和配置,在此不多介绍。 接下来文件的配置。 官网下载并解压Flutter SDK 版本列表 - Flutter 中文文档

    2023年04月25日
    浏览(30)
  • Android下载apk并安装apk(用于软件版本升级用途)

    软件版本更新是每个应用必不可少的功能,基本实现方案是请求服务器最新的版本号与本地的版本号对比,有新版本则下载apk并执行安装。请求服务器版本号与本地对比很容易,本文就不过多讲解,主要讲解下载apk到安装apk的内容。 (1)读写外部存储的权限需要动态申请,

    2024年02月01日
    浏览(57)
  • Ansible playbook简介与初步实战,实现批量机器应用下载与安装

    playbook是ansible用于配置,部署,和管理被节点的剧本 通过playbook的详细描述,执行其中的一些列tasks,可以让远端的主机达到预期的状态。playbook就像ansible控制器给被控节点列出的一系列to-do-list,而且被控节点必须要完成 playbook顾名思义,即剧本,现实生活中演员按照剧本表

    2024年02月09日
    浏览(27)
  • 【Flutter】如何更改 Flutter 应用的启动图标

    欢迎来到 Flutter 的世界!在这篇文章中,我们将探索 Flutter 的一些基础知识。但是,你知道吗?这只是冰山一角。如果你想深入学习 Flutter,掌握更多的技巧和最佳实践,我有一个好消息要告诉你:我们有一个全面的 Flutter专栏-Flutter Developer 101 入门小册 等待着你。在那里,你

    2024年02月08日
    浏览(31)
  • Qt应用开发——下载安装和HelloWorld

            工欲善其事,必先利其器。第一步环境安装好是必要的过程。Qt 在23年4月份已经更新到了6.5.0,相对于其他的工具,Qt不断在维护升级这一点就非常的友好,这里对版本的迭代更新内容不做介绍,做应用开发的话肯定是版本越新最好。官网下载的每个版本都提供了

    2024年02月16日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包