Code前端首页关于Code前端联系我们

适用于 Android 开发者的 Flutter 插件开发自动安装 APK

terry 2年前 (2023-09-23) 阅读数 69 #移动小程序

什么是 Flutter 插件

Flutter 插件是一个特殊的包,其中包含用 Dart 编写的 API 定义,它结合了特定于 Android 和 iOS 平台的实现,因此实现两者的兼容。

  • 应用程序的Flutter部分通过平台通道
  • 平台通道向其应用程序所在的主机(iOS或Android)发送消息,主机监听并接收消息。然后,它调用特定于该平台的 API(使用本机编程语言),并将响应发送回客户端,即。 Flutter应用程序的一部分使用平台通道在客户端(Flutter UI)和主机(平台)之间传输消息如下图
    Flutter插件开发之APK自动安装,适用于Android开发人员

创建Flutter应用程序

相关代码请参见运行第一个Flutter应用程序

创建Flutter插件

右键project->New->Module如下图Flutter插件开发之APK自动安装,适用于Android开发人员

选择Flutter Plugin,点击Next如下图Flutter插件开发之APK自动安装,适用于Android开发人员

输入项目名称(Project name),点击Next,如下图Flutter插件开发之APK自动安装,适用于Android开发人员

输入包名(Package name),点击Finish如下图Flutter插件开发之APK自动安装,适用于Android开发人员

即可创建此Flutter插件。

引入插件

在项目目录下找到文件pubspec.yaml,在dev_dependency中添加如下依赖,如下图Flutter插件开发之APK自动安装,适用于Android开发人员

的对应代码如下

获取版本号表示

打开lib插件下的dart文件,平台会自动生成专门用于获取APP版本号的代码如下代码

class InstallApkPlugin {
  static const MethodChannel _channel =
      const MethodChannel('install_apk_plugin');

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

}
复制代码

java部分代码为如下所示

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

    private final Registrar registrar;

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

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

    @Override
    public void onMethodCall(MethodCall call, Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        } else {
            result.notImplemented();
        }
    }

}
复制代码

实现自动安装APK

要执行自动安装APK,需要将APK安装包的地址从Flutter应用层传递到主机层。 Dart代码如下:

class InstallApkPlugin {
  static const MethodChannel _channel =
      const MethodChannel('install_apk_plugin');

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Future<bool> installApk(String path) async {
    final bool isSuccess = await _channel.invokeMethod('installApk', path);
    return isSuccess;
  }
}
复制代码

java部分的代码如下

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

    private final Registrar registrar;

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

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

    @Override
    public void onMethodCall(MethodCall call, Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        } else if (call.method.equals("installApk")) {
            final String path = (String) call.arguments;
            Log.d(TAG, "installApk path is " + path);
        } else {
            result.notImplemented();
        }
    }
}
复制代码

就是这样。主机层可以获取APK安装包的路径。然后你只需要实现Android APK安装程序代码逻辑。在日志下面添加以下代码

    File file = new File(path);
    installApk(file, registrar.context());
复制代码

installApk代码实现如下

    private void installApk(File apkFile, Context context) {
        Intent installApkIntent = new Intent();
        installApkIntent.setAction(Intent.ACTION_VIEW);
        installApkIntent.addCategory(Intent.CATEGORY_DEFAULT);
        installApkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        Uri apkUri = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
            installApkIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            apkUri = Uri.fromFile(apkFile);
        }
        installApkIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");

        if (context.getPackageManager().queryIntentActivities(installApkIntent, 0).size() > 0) {
            context.startActivity(installApkIntent);
        }
    }
复制代码

除此之外。另外,还需要将AndroidManifest.xml中的代码更改为如下代码

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.yuzo.install_apk_plugin">

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

    <application>
        <!--provider start-->
        <provider
            android:name="androidx.core.content.FileProvider"
            tools:replace="android:authorities"
            android:authorities="com.yuzo.opengit.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                tools:replace="android:resource"
                android:resource="@xml/file_path" />
        </provider>
        <!--provider end-->
    </application>
</manifest>
复制代码

file_path.xml并将其放在res->xml文件夹下,如下所示代码

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="ResourceName">

    <root-path
        name="root_path"
        path="." />

</paths>
复制代码

运行代码如下Flutter插件开发之APK自动安装,适用于Android开发人员

作者:Yuzo
链接:https://juejin.im/post/5d021b68e51d45777621bb65
来源:掘金
版权归作者所有。商业转载请联系作者获得许可。非商业转载请注明来源。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门