上一篇文章Android 混合Flutter之源碼集成方式有優勢和也有缺點:html
優勢java
缺點android
Flutter
而且都要安裝Flutter
環境Flutter
項目和Native
項目Flutter
會直接侵入到Native
項目中去Android
混合Flutter
除了上面所說的源碼集成方式還有沒有其餘方式呢?答案確定是有的,那就是Flutter
以產物的方式集成到Native
,簡而言之將開發的Flutter
項目單獨編譯成aar文件,而後以組件的形式被主工程(Native工程)依賴,aar
文件能夠以maven方式(遠程方式)的依賴,本文主要爲了體驗產物集成和源碼集成方案對比,就先用本地依賴的方式來集成。ios
這裏和源碼集成不一樣的是在New Flutter Project
選擇的是Flutter Application
而不是Flutter Module
:git
Flutter
項目的
dart
文件拉到這個項目中,代碼就不貼出來了,主要是根據路由去跳轉不一樣的頁面。
首先看android
目錄下build.gradle
:github
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
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
依賴了mergeAssets
和flutterTask
,也就是當mergeAssets
(Android的assets處理完成後)和flutterTask
(flutter編譯完)和執行完,Flutter
產物就會被copyFlutterAssetsTask
根據debug仍是release複製到build/app/intermediates/merged_assets/debug/mergeDebugAssets/out
或者build/app/intermediates/merged_assets/release/mergeReleaseAssets/out
,Flutter
的編譯產物,具體是在flutterTask
的getAssets
方法指定的:架構
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
構建代碼:
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
模式下的產物:
isolate_snapshot_instr
和
vm_snapshot_instr
,由於在
debug
下只會執行一個命令
flutter build bundle
,它會生成
assets
、
vm_snapshot_data
、
isolate_snapshot_data
。
release
模式下,會執行兩個命令:
flutter build aot
,
flutter build bundle --precomiled
,
Android
默認使用
app-aot-blobs
,這種模式會生成
isolate_snapshot_data
、
isolate_snapshot_instr
、
vm_snapshot_data
和
vm_snapshot_instr
四個文件,多生成兩個文件只要是爲了執行速度更快。
assets
文件夾有isolate_snapshot_instr
,flutter_assets
,vm_snapshot_data
,vm_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之間的常見例程指令。lib文件夾是特定平臺(arm或者x86)的so文件,Flutter
在Android
平臺下會默認生成arm-v7
架構的so庫,debug模式下同時生成x86_64、x86和arm64-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/"
}
複製代碼
本文暫時還不須要用到這兩步。
上面經過編譯命令獲得apk,那麼若是想打包aar,只要把app/build.gradle
中的apply plugin: 'com.android.application'
改成apply plugin: 'com.android,library'
而且把applicationId "com.example.flutter_app"
註釋
android
目錄下的
AndroidManifest.xml
把
android:label="xxx"
和
android:name="xxxxx"
註釋掉:
在
Terminal
執行下面命令,就能獲得
app-release.aar
文件
首先建立完Android項目,將上面打包成功的aar文件
以普通的aar
集成到Android項目中去,首先將aar
文件拷貝到libs
目錄下:
app
模塊下配置
build.gradle
,對
aar
文件的依賴
這時候你會發現沒有
Flutter
類和
FlutterFragment
,在
Android 混合Flutter之源碼集成方式有提過,建立
Flutter Module
的時候,在
.android
->
Flutter
->
io.flutter
->
facade
會生成兩個
java
文件,分別是
Flutter
和
FlutterFragment
:
下面把這兩個文件複製過來:
最後Android
原生調用
Flutter
方式:
@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;
}
複製代碼
@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();
}
複製代碼
@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的方法來實現。
若是想要以混編的方式來開發項目,能夠自行根據這兩種方案的特色來選擇,下面附上兩種方案的優缺點: