Android 混合Flutter之產物集成方式

1、前言

上一篇文章Android 混合Flutter之源碼集成方式有優勢和也有缺點:html

優勢java

  • 1.簡單快捷,Google原生支持
  • 2.開發調試方便,和原生交互較多或須要依賴原生數據環境的時候特別能體現出來

缺點android

  • 1.團隊全部人均可能要會Flutter而且都要安裝Flutter環境
  • 2.須要對現有的編譯體系作出修改,也就是要同時編譯Flutter項目和Native項目
  • 3.Flutter會直接侵入到Native項目中去
  • 4.編譯速度慢

Android混合Flutter除了上面所說的源碼集成方式還有沒有其餘方式呢?答案確定是有的,那就是Flutter以產物的方式集成到Native,簡而言之將開發的Flutter項目單獨編譯成aar文件,而後以組件的形式被主工程(Native工程)依賴,aar文件能夠以maven方式(遠程方式)的依賴,本文主要爲了體驗產物集成和源碼集成方案對比,就先用本地依賴的方式來集成。ios

2、Flutter項目

1.編寫Flutter項目代碼

這裏和源碼集成不一樣的是在New Flutter Project選擇的是Flutter Application而不是Flutter Modulegit

建立Flutter項目
項目結構具體以下:

項目結構
把上一篇源碼集成 Flutter項目的 dart文件拉到這個項目中,代碼就不貼出來了,主要是根據路由去跳轉不一樣的頁面。

2.build.gradle

首先看android目錄下build.gradle:github

build.gradle
若是作過安卓領域的同窗對這個文件很熟悉了,在原生安卓項目 app模塊下也有這個文件,這個文件是 app模塊的 gradle構建腳本,通常用來管理app包名、版本號以及添加修改依賴庫,在 Flutter項目中,這個文件是由 Flutter SDK生成的,相比原生安卓工程有些許不一樣,固然若是你根據 gradle的知識體系來理解就行,下面看看這個文件:

//取得`local.properties`中的關於Flutter相關屬性
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}
//獲取flutter.sdk信息
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.")
}

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

//獲取flutter.versionName
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

//指定爲應用程序模塊
apply plugin: 'com.android.application'
//引用flutter.gradle
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    //編譯版本
    compileSdkVersion 28
    //lint配置
    lintOptions {
        disable 'InvalidPackage'
    }
    
    //基本配置信息 包名,最低支持版本號 版本號 版本名字等
    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.flutter_app"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    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 {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
複製代碼

apply from:"$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"這句話是引入flutter.gradle配置模塊,能夠這麼理解向普通Android工程打包流程插入一些Flutter Task任務,簡單的話用一下一張圖描述:json

gradle執行順序
flutter.gradle源碼 大致結構以下:

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
    }
}

android {
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}

apply plugin:FlutterPlugin
class FlutterPlugin implements Plugin<Project>{...}
class FlutterExtension {...}
abstract FlutterTask extends BaseFlutterTask{...}
gradle.useLogger(new FlutterEventLogger)
class FlutterEventLogger extends BuildAdapter implements TaskExecutinListener{...}
複製代碼

flutter.gradle配置了一個名爲FlutterPlugin的插件,這個插件實現了Plugin<Project>接口的apply方法,這是標準的gradle plugin,那麼它確定會定義一些task和必要的依賴,在addFlutterTask這個方法能夠體現:api

.....
           // We know that the flutter app is a subproject in another Android
           // app when these tasks exist.
           //咱們知道flutter應用程序是另外一個安卓系統的子項目
            Task packageAssets = project.tasks.findByPath(":flutter:package${variant.name.capitalize()}Assets")
            Task cleanPackageAssets = project.tasks.findByPath(":flutter:cleanPackage${variant.name.capitalize()}Assets")
            Task copyFlutterAssetsTask = project.tasks.create(name: "copyFlutterAssets${variant.name.capitalize()}", type: Copy) {
                dependsOn compileTasks if (packageAssets && cleanPackageAssets) {
                    //擋在flutter模塊中,存在cleanPackageAssets和packageAssets時
                    dependsOn packageAssets
                    dependsOn cleanPackageAssets
                    into packageAssets.outputDir
                } else {
                    //依賴於mergeAssets任務
                    dependsOn variant.mergeAssets
                    //依賴於cleanAssets任務
                    dependsOn "clean${variant.mergeAssets.name.capitalize()}"
                    variant.mergeAssets.mustRunAfter("clean${variant.mergeAssets.name.capitalize()}")
                    into variant.mergeAssets.outputDir
                }
                compileTasks.each { flutterTask ->
                    //執行flutterTask的getAssets方法
                    with flutterTask.assets
                }
            }
            //processResource依賴於copyFlutterAssetsTask
            variant.outputs.first().processResources.dependsOn(copyFlutterAssetsTask)
複製代碼

從上面源碼能夠看出processResource這個Task依賴於copyFlutterAssetsTask,意思是要先執行完copyFlutterAssetsTask才能執行processResource,看英文意思就把flutter相關Task加到gradle的編譯流程中,另外copyFlutterAssetsTask依賴了mergeAssetsflutterTask,也就是當mergeAssets(Android的assets處理完成後)和flutterTask(flutter編譯完)和執行完,Flutter產物就會被copyFlutterAssetsTask根據debug仍是release複製到build/app/intermediates/merged_assets/debug/mergeDebugAssets/out或者build/app/intermediates/merged_assets/release/mergeReleaseAssets/outFlutter的編譯產物,具體是在flutterTaskgetAssets方法指定的:架構

class FlutterTask extends BaseFlutterTask {
    @OutputDirectory
    File getOutputDirectory() {
        return intermediateDir
    }

    CopySpec getAssets() {
        return project.copySpec {
            from "${intermediateDir}"
            include "flutter_assets/**" // the working dir and its files
        }
    }
    ......
}
複製代碼

也就是說,這些產物就是build/app/intermediates/flutter/xxx(xxx指debug或者release)下面的flutter_assets/目錄中的全部內容,那如今在命令行輸入打包命令flutter build apk,會編譯生成apk文件,路徑位於build/app/outputs/apk/release/app-release.apk,注意若是你輸入flutter build apk,實際默認打release包,也就是等價於flutter build --release,若是須要打debug包,能夠輸入flutter build apk --debug:app

Flutter_build_apk

Flutter產物分析
能夠生成不少產物,這些產物都是來自 Flutter構建代碼:

final String assembly = fs.path.join(outputDir.path, 'snapshot_assembly.S');                                              
if (buildSharedLibrary || platform == TargetPlatform.ios) {                                                               
  // Assembly AOT snapshot. 
  outputPaths.add(assembly);                                                                                              
  genSnapshotArgs.add('--snapshot_kind=app-aot-assembly');                                                                
  genSnapshotArgs.add('--assembly=$assembly');                                                                            
} else {                                                                                                                  
  // Blob AOT snapshot. 
  final String vmSnapshotData = fs.path.join(outputDir.path, 'vm_snapshot_data');                                         
  final String isolateSnapshotData = fs.path.join(outputDir.path, 'isolate_snapshot_data');                               
  final String vmSnapshotInstructions = fs.path.join(outputDir.path, 'vm_snapshot_instr');                                
  final String isolateSnapshotInstructions = fs.path.join(outputDir.path, 'isolate_snapshot_instr');                      
  outputPaths.addAll(<String>[vmSnapshotData, isolateSnapshotData, vmSnapshotInstructions, isolateSnapshotInstructions]); 
  genSnapshotArgs.addAll(<String>[                                                                                        
    '--snapshot_kind=app-aot-blobs',                                                                                      
    '--vm_snapshot_data=$vmSnapshotData',                                                                                 
    '--isolate_snapshot_data=$isolateSnapshotData',                                                                       
    '--vm_snapshot_instructions=$vmSnapshotInstructions', 
複製代碼

看看debug模式下的產物:

Flutter下debug下的產物
能夠發現lib文件下多了 x86_64x86arm64-v8a文件並對應的so文件,而且少了 isolate_snapshot_instrvm_snapshot_instr,由於在 debug下只會執行一個命令 flutter build bundle,它會生成 assetsvm_snapshot_dataisolate_snapshot_datarelease模式下,會執行兩個命令: flutter build aotflutter build bundle --precomiledAndroid默認使用 app-aot-blobs,這種模式會生成 isolate_snapshot_dataisolate_snapshot_instrvm_snapshot_datavm_snapshot_instr四個文件,多生成兩個文件只要是爲了執行速度更快。

3.產物分析

3.1.assets文件夾

assets文件夾有isolate_snapshot_instrflutter_assetsvm_snapshot_datavm_snapshot_instr

  • flutter_assets:是Flutter工程產生的assets文件,包含字體文件,協議等。
  • isolate_snapshot_instr:包含由Dart isolate執行的AOT代碼。
  • isolate_snapshot_data:表示isolates堆存儲區的初始狀態和特定的信息,和vm_snapshot_data配合,更快啓動Dart_VM。
  • vm_snapshot_data:表示isolates之間共享的Dart堆存儲區的初始狀態,用於更快的啓動Dart VM。
  • vm_snapshot_instr:包含VM中全部的isolates之間的常見例程指令。

3.2.lib文件夾

lib文件夾是特定平臺(arm或者x86)的so文件,FlutterAndroid平臺下會默認生成arm-v7架構的so庫,debug模式下同時生成x86_64x86arm64-v8a的so文件,固然有的項目可能配置了

ndk{
    abiFilters 'armeabi'
}
複製代碼

爲了解決so對其問題,須要在Flutter項目中手動armeabi的so文件,這樣的話打包出來就aar包含了armeabi的so文件,這個armeabi的so文件能夠拷貝armeabi-v7下面的,通常狀況下他們兩個是沒什麼區別,在app目錄下建立libs/armeabi,而後將libflutter.so拷貝到armeabi的目錄下,而後在gradle中配置

android{
	sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
}
複製代碼

由於Flutter SDK版本速度很快,每一個版本打出的so文件可能稍有不一樣,全部只要升級sdk可能就須要拷貝so文件,比較麻煩,因此能夠監聽打包aar的任務來進行自動拷貝,在gradle文件中配置如下代碼

//如下任務爲了拷貝so 由於Flutter默認只生成v7的so
task copyFlutterSo(dependsOn: 'transformNativeLibsWithSyncJniLibsForRelease', type: Copy) {
    //${buildDir} = /Users/xueshanshan/project/flutter/flutter_debug_library/build/app
    def dir = "${buildDir}/intermediates/library_and_local_jars_jni/release"
    from "${dir}/armeabi-v7a/libflutter.so"
    into "${dir}/armeabi/"
}
複製代碼

本文暫時還不須要用到這兩步。

4.打包aar文件

上面經過編譯命令獲得apk,那麼若是想打包aar,只要把app/build.gradle中的apply plugin: 'com.android.application'改成apply plugin: 'com.android,library' 而且把applicationId "com.example.flutter_app"註釋

打包aar文件一
android目錄下的 AndroidManifest.xmlandroid:label="xxx"android:name="xxxxx"註釋掉:

AndroidMenifest.xml文件配置
Terminal執行下面命令,就能獲得 app-release.aar文件

  • flutter clean
  • cd android
  • ./gradlew assembleRelease

獲得aar文件

3、Android項目

首先建立完Android項目,將上面打包成功的aar文件以普通的aar集成到Android項目中去,首先將aar文件拷貝到libs目錄下:

添加aar文件
而且在 app模塊下配置 build.gradle,對 aar文件的依賴

添加aar文件依賴
這時候你會發現沒有 Flutter類和 FlutterFragment,在 Android 混合Flutter之源碼集成方式有提過,建立 Flutter Module的時候,在 .android-> Flutter-> io.flutter-> facade會生成兩個 java文件,分別是 FlutterFlutterFragment

  • Flutter:Android應用程序中使用Flutter的主要入口點
  • FlutterFragment:Fragment來管理FlutterView

下面把這兩個文件複製過來:

添加Flutter和FlutterFragment
最後 Android原生調用 Flutter方式:

  • 繼承FlutterActivity
@Override
    public FlutterView createFlutterView(Context context){
        getIntentData();
        WindowManager.LayoutParams matchParent = new WindowManager.LayoutParams(-1, -1);
        //建立FlutterNativeView
        FlutterNativeView nativeView = this.createFlutterNativeView();
        //建立FlutterView
        FlutterView flutterView = new FlutterView(FlutterMainActivity.this,(AttributeSet)null,nativeView);
        //給FlutterView傳遞路由參數
        flutterView.setInitialRoute(routeStr);
        //FlutterView設置佈局參數
        flutterView.setLayoutParams(matchParent);
        //將FlutterView設置進ContentView中,設置內容視圖
        this.setContentView(flutterView);
        return flutterView;
    }

複製代碼
  • 繼承AppCompatActivity
@Override
    protected void onCreate(@Nullable Bundle savedInstanceStae){
        super.onCreate(savedInstanceStae);

        String route = getIntent().getStringExtra("_route_");
        String params = getIntent().getStringExtra("_params_");
        JSONObject jsonObject = new JSONObject();
        try{
            jsonObject.put("pageParams",params);
        } catch(JSONException e){
            e.printStackTrace();

        }
        //將FlutterView設置進ContentView中,設置內容視圖
        //建立FlutterView
        flutterView = Flutter.createView(this,getLifecycle(),route + "?" + jsonObject.toString());
        //設置顯示視圖
        setContentView(flutterView);
        //插件註冊
        registerMethodChannel();

    }
複製代碼
  • Fragment方式:
@Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
        Log.d(TAG,"onCreateView-mRoute:"+mRoute);

        mFlutterView = Flutter.createView(getActivity(),getLifecycle(),mRoute);
        //綜合解決閃屏,佈局覆蓋問題
        mFlutterView.setZOrderOnTop(true);
        mFlutterView.setZOrderMediaOverlay(false);
        mFlutterView.getHolder().setFormat(Color.parseColor("#00000000"));

        //註冊channel
       // GeneratedPluginRegistrant.registerWith(mFlutterView.getPluginRegistry());
        //返回FlutterView
        return mFlutterView;
    }
複製代碼

實際效果以下圖:

最終效果圖

注意 這裏會牽扯到若是Flutter工程依賴了第三方的Flutter plugin那麼打包aar文件的時候是沒法把Plugin內容打進去的,網上有文章說能夠用fataar-gradle-plugin或者fat-aar-android,找遍gradle沒找到修改的地方,能夠採用這兩篇文章把flutter項目做爲aar添加到已有的Android工程上Flutter混編一鍵打包並上傳maven的方法來實現。

4、總結

若是想要以混編的方式來開發項目,能夠自行根據這兩種方案的特色來選擇,下面附上兩種方案的優缺點:

優缺點對比

5、參考資料

6、源碼案例

本博文例子Flutter端

本博文例子Android端

相關文章
相關標籤/搜索