Flutter插件開發(fā)之APK自動安裝

Flutter插件開發(fā)之APK自動安裝

本文適用于Android開發(fā)人員

個人博客

什么是Flutter Plugin

Flutter Plugin是一種特殊的包,包含一個用Dart編寫的API定義,結合Android和iOS的平臺特定實現(xiàn),從而達到二者兼容。

  • 應用的Flutter部分通過平臺通道(platform channel)將消息發(fā)送到其應用程序的所在的宿主(iOS或Android)
  • 宿主監(jiān)聽的平臺通道,并接收該消息。然后它會調用特定于該平臺的API(使用原生編程語言) - 并將響應發(fā)送回客戶端,即應用程序的Flutter部分
    使用平臺通道在客戶端(Flutter UI)和宿主(平臺)之間傳遞消息,如下圖所示


    enter image description here

創(chuàng)建Flutter App

相關代碼見運行第一個Flutter App

創(chuàng)建Flutter Plugin

右鍵工程->New->Module,如下圖所示


enter image description here

選擇Flutter Plugin,點擊Next,如下圖所示


enter image description here

輸入工程名(Project name),點擊Next,如下圖所示
enter image description here

輸入包名(Package name),點擊Finish,入下圖所示


enter image description here

到此Flutter plugin創(chuàng)建完成。

引入插件

在工程目錄下找到pubspec.yaml文件,在dev_dependencies添加如下依賴,如下圖所示

enter image description here

相關代碼如下

dev_dependencies:
  flutter_test:
    sdk: flutter
  install_apk_plugin:
    path: install_apk_plugin

獲取版本號demo

打開插件lib下的dart文件,會有平臺自動生成的代碼,具體是實現(xiàn)獲取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();
        }
    }

}

實現(xiàn)自動安裝APK

實現(xiàn)自動安裝APK,需要從Flutter應用層傳入一個APK安裝包的地址到host層,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();
        }
    }
}

到此,host層就能獲取到APK安裝包的路徑了,后面只需實現(xiàn)Android安裝APK的代碼邏輯即可,在日志下面添加如下代碼

    File file = new File(path);
    installApk(file, registrar.context());

installApk代碼實現(xiàn)如下所示

    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>

運行代碼如下圖所示


enter image description here

源代碼

項目地址-OpenGit客戶端

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容