As we all know, whether it is Flutter or uni-app, it is actually a UI framework, and they all run on the native system. Naturally, we can integrate uni-app in the Flutter project.
Android integrated uni-app
1. Download offline SDK
First, we create a Flutter ordinary application and use Android Studio to open the Android project. Next, open uni-app official website, download the latest offline Android the SDK , as shown below.
After decompression, you can use Android Studio to open the project HBuilder-Integrate-AS inside to view the running effect. Open the downloaded uni-app SDK directory, as shown in the figure below.
The SDK directory description is as follows:
|-- HBuilder-Hello App离线打包演示应用
|-- HBuilder-Integrate-AS 集成uni-app的最简示例
|-- SDK SDK库文件目录
|-- Feature-Android.xls Android平台各扩展Feature API对应的详细配置
|-- Readme.txt 版本说明文件及注意事项
|-- UniPlugin-Hello-AS uni原生插件开发示例
Two, configuration engineering
2.1 Basic library configuration
Then, let's take a look at how to integrate the uni-app SDK in the native Android project. If you don’t have a native Android project yet, you can create a new one. Then, copy lib.5plus.base-release.aar, android-gif-drawable-release@1.2.17.aar, uniapp-v8-release.aar and oaid_sdk_1.0.25.aar to the libs directory.
Add resource reference in build.gradle. Since the above are all aar methods, you only need to add include: ['*.aar', '*.jar']
to import it.
implementation fileTree(dir: 'libs', include: ['*.aar', '*.jar'], exclude: [])
implementation "com.android.support:support-v4:28.0.0"
implementation "com.android.support:appcompat-v7:28.0.0"
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.facebook.fresco:fresco:1.13.0'
implementation "com.facebook.fresco:animated-gif:1.13.0"
implementation 'com.github.bumptech.glide:glide:4.9.0'
implementation 'com.alibaba:fastjson:1.1.46.android'
When configuring uni-app, you also need to add the aaptOptions configuration in the android node of build.gradle, as shown below.
aaptOptions {
additionalParameters '--auto-add-overlay'
ignoreAssetsPattern "!.svn:!.git:.*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~"
}
2.2 Application configuration
Configure Appkey
Starting from version 3.1.10, you need to apply for Appkey to integrate uni-app. For apply for Appkey, please refer to .
Then, open Androidmanifest.xml, navigate to the Application node, and create a meta-data node, the name is dcloud_appkey, and the value is the applied AppKey.
<application
...>
<meta-data
android:name="dcloud_appkey"
android:value="替换为自己申请的Appkey" />
Configure the application version number
If you need to change the version and other information, you can modify the configuration under the defaultConfig node.
- versionCode : is the version number of the application (integer value), used for the upgrade judgment of each application market, it is recommended to be consistent with the version -> code value in manifest.json
- versionName : is the version name (string) of the application. The version number displayed in the system application management program is recommended to be consistent with the version -> name value in manifest.json.
- applicationId : is the package name of the application, generally set to the reverse domain name, and it is not recommended to modify it.
At the same time, it is recommended to set targetSdkVersion to 25 or above. App offline SDK minSdkVersion supports at least 21, less than 21 will not work normally on some models below 5.0.
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.aar', '*.jar'], exclude: [])
implementation 'com.github.bumptech.glide:glide:4.9.0' // 基座依赖
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.alibaba:fastjson:1.1.46.android'
}
Configure application startup page and provider node
Open the Androidmanifest.xml file, and the newly created project will have a MainActivity node by default, which must be deleted. Refer to the code below for other additions.
<activity
android:name="io.dcloud.PandoraEntry"
android:configChanges="orientation|keyboardHidden|keyboard|navigation"
android:label="@string/app_name"
android:launchMode="singleTask"
android:hardwareAccelerated="true"
android:theme="@style/TranslucentTheme"
android:screenOrientation="user"
android:windowSoftInputMode="adjustResize" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="io.dcloud.PandoraEntryActivity"
android:launchMode="singleTask"
android:configChanges="orientation|keyboardHidden|screenSize|mcc|mnc|fontScale|keyboard"
android:hardwareAccelerated="true"
android:permission="com.miui.securitycenter.permission.AppPermissionsEditor"
android:screenOrientation="user"
android:theme="@style/DCloudTheme"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<action android:name="android.intent.action.VIEW" />
<data android:scheme="h56131bcf" />
</intent-filter>
</activity>
<!--provider节点必须添加-->
<provider
android:name="io.dcloud.common.util.DCloud_FileProvider"
android:authorities="${apk.applicationId}.dc.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/dcloud_file_provider" />
</provider>
Other configuration
Before the formal packaging, you also need to configure the application icon and startup interface.
- icon.png is the application icon.
- push.png is the icon of the push message.
- splash.png is the icon of the application splash page.
Note: splash.png displays different effects on different devices. To prevent stretching, it is recommended to use Android studio to generate .9.png type pictures.
Resource allocation
Create a new assets folder manually, the location is at the same level as the java directory. Then, copy the SDK->assets->data folder to the assets folder, as shown in the figure below.
Then, create an apps folder under the assets folder, and copy the resources exported by the HBuilderX project to the assets->apps file, as shown in the following figure.
Generate HBuilderX project resources can refer to: Generate local packaged APP resources . Select Project -> Release -> Native App-Local Packaging -> Generate Local Packaged App Resources.
After completing the above operations, you need to modify the dcloud_control.xml file to ensure that the appid in dcloud_control.xml and the id in manifest.json are consistent with the folder name, as shown in the following figure.
To generate a custom base, you need to add debug="true"
and syncDebug="true"
under the root node, as shown in the figure below.
This custom base supports hot updates and needs to enter debug-server-release.aar into the apk, and it can be deleted when the official package is generated. You can refer to: detailed steps, please refer to the link .
Finally, just run it in the same way as the Android code, and the effect is as shown in the figure below.
iOS integrated uni-app
1. Download offline SDK
Like the native iOS project integrating other SDKs, the integration of uni-app in the Flutter project requires downloading the offline SDK first. Open the uni-app official website and download the latest offline SDK iOS.
After decompression, the directory structure of the file is as shown in the figure below.
|-- HBuilder-Hello 给用户打uni-app项目的离线打包工程
|-- Feature-iOS.xls 配置表(依赖的库、资源文件、参数配置等)
|-- SDK 工程需要的库文件,.h头文件,配置文件,资源文件
We can run the HBuilder-Hello project directly to see the running effect.
Two, add the basic dependency library and resource files
The basic dependent libraries and resources must be introduced into the project. The basic dependent libraries and resources are stored in the UniMPSDK/Core directory. The directory structure is shown below.
|-- UniMPSDK/Core
|-- Headers // .h 头文件
|-- Libs // 基础依赖库
|-- Resources // 资源文件
2.1 Add basic library
Use Xcode to open the iOS project, then select the project name in the directory on the left side of the Xcode project, click the [+] button in [TARGETS] -> [Build Phases] -> [Link Binary With Libaries], and click [Add] in the pop-up window Other] -> [Add Files...], then open the UniMPSDK/Core/Libs basic dependent library directory, select the .a library and .framework library in the directory, and click the open button to add the dependent library to the project.
2.2 Add system dependency library
Select the project name in the directory on the left side of the Xcode project, click the "+" button in TARGETS->Build Phases-> Link Binary With Libaries, find and select the required library in the pop-up window (see the table below), click " Add" button to add the library file to the project.
The libraries that need to be dependent are as follows:
- JavaScriptCore.framework
- CoreMedia.framework
- MediaPlayer.framework
- AVFoundation.framework
- AVKit.framework
- GLKit.framework
- OpenGLES.framework
- CoreText.framework
- QuartzCore.framework
- CoreGraphics.framework
- libc++.tbd
- QuickLook.framework
- CoreTelephony.framework
- AssetsLibrary.framework
- CoreLocation.framework
- AddressBook.framework
- libiconv.tbd
2.3 Add dependent resource files
Next, you need to add dependent resource files. It is recommended to create a new Group in the project to manage resource files. For example, create the UniMP folder in the project directory, and then create different directories to store the resource files according to the function module; Add resource file method: select the location of the imported resource file in the left directory (UniMP/Core in the example), In the right-click menu, select Add Files to "Project Name...", then open the UniMPSDK/Core directory, select the Resources folder, and then click "Add" to add the resource files to the project.
2.4 Add .h header file
Select the location of the imported header file in the directory on the left side of Xcode (UniMP/Core in the example), select Add Files to "Project Name..." in the right-click menu, then open the UniMPSDK/Core directory, select the Headers folder, and then Click "Add" to add the header file resources to the project.
Generate applet application resources
First select your uni-app project in HBuilderX, if not, please create a new uni-app project, as shown in the figure below.
Then, select your project, right click -> publish -> native App-make application wgt package.
Click "Browse", select the wgt package export path, and click "Generate wgt", as shown in the figure below.
After the project is compiled, the path of the wgt package will be output in the console. Click the path to open the directory where the wgt resource package is located.
Fourth, import applet resources
Open the native project directory and create a folder named Apps in the UniMP path, and copy the previously exported wgt package to the Apps folder, as shown in the figure below.
Then, select the location of the imported resource file in the left directory of the native project (UniMP/ in the example), select Add Files to "Project Name..." in the right-click menu, then open the project directory and select the Apps folder, Then click "Add" to add the application resource package to the project, as shown in the figure below.
Five, modify the code
First of all, you need to initialize the SDK engine and set the startup parameters. It is recommended application:didFinishLaunchingWithOptions
method, and reference the header files #import "DCUniMP.h"
and #import "WeexSDK.h"
in AppDelegate.m, as shown below.
#import "DCUniMP.h"
#import "WeexSDK.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// 配置参数
NSMutableDictionary *options = [NSMutableDictionary dictionaryWithDictionary:launchOptions];
// 设置 debug YES 会在控制台输出 js log,默认不输出 log,注:需要引入 liblibLog.a 库
[options setObject:[NSNumber numberWithBool:YES] forKey:@"debug"];
// 初始化引擎
[DCUniMPSDKEngine initSDKEnvironmentWithLaunchOptions:options];
// 注册 module 注:module的 Name 需要保证唯一, class:为 module 的类名
[WXSDKEngine registerModule:@"TestModule" withClass:NSClassFromString(@"TestModule")];
// 注册 component 注:component 的 Name 需要保证唯一, class:为 component 的类名
[WXSDKEngine registerComponent:@"testmap" withClass:NSClassFromString(@"TestMapComponent")];
return YES;
}
Then, call SDK related methods in the life cycle method of AppDelegate.m App, as shown below.
#pragma mark - App 生命周期方法
- (void)applicationDidBecomeActive:(UIApplication *)application {
[DCUniMPSDKEngine applicationDidBecomeActive:application];
}
- (void)applicationWillResignActive:(UIApplication *)application {
[DCUniMPSDKEngine applicationWillResignActive:application];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
[DCUniMPSDKEngine applicationDidEnterBackground:application];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
[DCUniMPSDKEngine applicationWillEnterForeground:application];
}
- (void)applicationWillTerminate:(UIApplication *)application {
[DCUniMPSDKEngine destory];
}
In addition, the following methods can also be implemented according to project requirements.
#pragma mark - 如果需要使用 URL Scheme 或 通用链接相关功能,请实现以下方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
// 通过 url scheme 唤起 App
[DCUniMPSDKEngine application:app openURL:url options:options];
return YES;
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
// 通过通用链接唤起 App
[DCUniMPSDKEngine application:application continueUserActivity:userActivity];
return YES;
}
Next, you need to add the following logic to the file of the applet, refer to the sample project ViewController.m. First, you need to quote the header file.
#import "DCUniMP.h"
Add the proxy protocol, DCUniMPEngineDelegate class, as follows.
@interface ViewController () <DCUniMPSDKEngineDelegate>
@end
The applet application resources must be deployed to the specified sandbox path to run normally, as follows.
/// 检查运行目录是否存在应用资源,不存在将应用资源部署到运行目录
- (void)checkUniMPResource {
// 注意:isExistsApp: 方法仅是判断运行目录中是否存在应用资源,正式环境应该添加版本控制,内置新的wgt资源后需要判断版本,决定是否需要释放应用资源
if (![DCUniMPSDKEngine isExistsApp:k_AppId]) {
// 读取导入到工程中的wgt应用资源
NSString *appResourcePath = [[NSBundle mainBundle] pathForResource:k_AppId ofType:@"wgt"];
// 将应用资源部署到运行路径中
if ([DCUniMPSDKEngine releaseAppResourceToRunPathWithAppid:k_AppId resourceFilePath:appResourcePath]) {
NSLog(@"应用资源文件部署成功");
}
}
}
Finally, the code to open the applet in the native code is as follows.
/// 打开 uni 小程序
- (IBAction)openUniMP:(id)sender {
// 初始化小程序的配置信息对象
DCUniMPConfiguration *configuration = [[DCUniMPConfiguration alloc] init];
[DCUniMPSDKEngine openUniMP:k_AppId configuration:configuration completed:^(DCUniMPInstance * _Nullable uniMPInstance, NSError * _Nullable error) {
if (uniMPInstance) {
// success
} else {
// error
}
}];
}
You can run through the sample code to see the effect.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。