Flutter打包AAR外掛之fat-aar使用教程

BugKingLiang發表於2020-07-13

Google推薦的打包AAR方式

在開始講解fat-aar外掛打包之前,先講講Google推薦的打包流程:

  1. 建立一個 flutter module 工程,建立方式有兩種

    1. 命令列方式建立: flutter create -t module --org com.example my_flutter
    2. Android Studio建立
      Flutter打包AAR外掛之fat-aar使用教程
  2. 執行打包命令 flutter build aar ,這個打包AAR方式會包含多種abi,如果想要指定abi可以使用 flutter build aar --target-platform xxx平臺

  3. 打包命令執行沒有報錯的情況下,控制檯會有最終打包aar檔案的存放地址如何使用整合到你應經存在的android專案中的提示說明.例如如下提示

Flutter打包AAR外掛之fat-aar使用教程

在已經存在的Android專案中嵌入Flutter工程,還有一種原始碼的方式,這裡就不在講解,如果你的英文水平比較好可以直接看官網的文件就可以了,這裡講的很清楚了.

fat-aar打包Flutter工程 (開源的Android打包AAR外掛)

看標題我說fat-aar外掛是Android打包AAR外掛,fat-aar是android工程中打包AAR的一個外掛.那個和Flutter有什麼關係呢?本質上說:上面講的Google推薦的打包AARfat-aar外掛打包AAR的原理是類似的.他們都是打包Android工程為一個AAR檔案

工程模式不同

  • Google打包的工程是: flutter-module
  • fat-aar打包的是一個純flutter工程
    Flutter打包AAR外掛之fat-aar使用教程
    也就是通過這方式建立的flutter工程.

正事開始之前講講flutter專案目錄結構

Flutter打包AAR外掛之fat-aar使用教程
可以看到在flutter專案的工程有個Android專案工程(如果你用在資料夾中開啟,他是一個.android的資料夾),然後右擊選中flutter->open Android module in Android Studio

開始整合fat-aar

  1. 修改.android/build.gradle檔案
buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        //增加這個配置
        classpath "com.kezong:fat-aar:1.2.15"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
複製程式碼

2.修改.android/app/build.gradle

//新增: 是否作為依賴
boolean isAarLibrary = true

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}
//新增:當需要打包aar 時,修改專案為library模式
if (isAarLibrary) {
    apply plugin: 'com.android.library'
} else {
    apply plugin: 'com.android.application'
}
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

//新增:引入fat-aar
if (isAarLibrary) {
    apply plugin: 'com.kezong.fat-aar'
}

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        //新增:需要打包aar時候,不能有applicationId
        if (!isAarLibrary) {
            applicationId "com.flutter.flutter_aar_demo"
        }
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }
    lintOptions {
        disable 'InvalidPackage'
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    
    //新增:將libflutter.so  和 flutter_embedding.jar ,同時和第三方外掛打包到aar中
    if (isAarLibrary) {

        // 新增 flutter_embedding.jar release 註釋①
        embed "io.flutter:flutter_embedding_release:1.0.0-ee76268252c22f5c11e82a7b87423ca3982e51a7"
        // 新增各個 cpu 版本 flutter.so 註釋②
//        embed "io.flutter:arm64_v8a_debug:1.0.0-eed171ff3538aa44f061f3768eec3a5908e8e852"
//        embed "io.flutter:armeabi_v7a_debug:1.0.0-eed171ff3538aa44f061f3768eec3a5908e8e852"
//        embed "io.flutter:x86_64_debug:1.0.0-eed171ff3538aa44f061f3768eec3a5908e8e852"
//        embed "io.flutter:x86_debug:1.0.0-eed171ff3538aa44f061f3768eec3a5908e8e852"

        embed "io.flutter:arm64_v8a_release:1.0.0-ee76268252c22f5c11e82a7b87423ca3982e51a7"
        embed "io.flutter:armeabi_v7a_release:1.0.0-ee76268252c22f5c11e82a7b87423ca3982e51a7"


        //新增fat-aar處理flutter打包成aar中三方依賴
        def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
        def plugins = new Properties()
        def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
        if (pluginsFile.exists()) {
            pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
        }
        plugins.each { name, _ ->
            
            embed project(path: ":$name", configuration: 'default')
            
        }

    }

}
複製程式碼

註釋①:如何查詢最新flutter_embedding.jar檔案的最新版本,也就是io.flutter:flutter_embedding_release:1.0.0-ee76268252c22f5c11e82a7b87423ca3982e51a7,release: 後面的版本號.最新版本號是預設儲存在這裡了,例如我window下的是(mac也是相同的.gradle/xxxx)

Flutter打包AAR外掛之fat-aar使用教程

.gradle\caches\modules-2\files-2.1\io.flutter 註釋②:同樣flutter.so也是儲存在.gradle\caches\modules-2\files-2.1\io.flutter 資料夾下

修改.android/app/AndroidManifest.xml 檔案

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.flutter.flutter_aar_demo"
    xmlns:tools="http://schemas.android.com/tools">
   //只保留application標籤
    <application>
    
        <!--從這裡開始註釋-->
        
       <!-- android:name="io.flutter.app.FlutterApplication"
        android:label="flutter_aar_demo"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            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">
            &lt;!&ndash; 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. &ndash;&gt;
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            &lt;!&ndash; Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. &ndash;&gt;
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <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>
複製程式碼

開始編譯打包

在Android專案下執行 gradlew assembleRelease,這是一個比較耗時的任務,靜靜的等待即可.

獲取aar檔案.

編譯完成後的檔案儲存在了你的flutter專案目錄下的build/app/outputs/arr/app-release.aar,獲取到這個.aar檔案後就可以直接扔給你的Android開發同學使用了.注意需要你的Android專案的開發同學開啟支援java8

fat-aar 和Google推薦的相同優缺點

優點:

  1. Android開發的同學不要配置flutter環境
  2. fat-aar:將flutter所有的需要的包全部打包大一個aar檔案下了.包括flutter專案下的第三方外掛.

缺點:

  1. 他們相同的缺點是相對於原始碼整合的方式缺少除錯flutter程式碼的功能.

最後

有寫的不對的地方,不吝賜教

相關文章