flutter_exit_app 三方库鸿蒙适配之旅:从零到一的深度实践
flutter_exit_app 三方库鸿蒙适配之旅:从零到一的深度实践
在数字化浪潮的推动下,跨平台开发框架如 Flutter 凭借其高效、便捷的特性,成为了开发者们的宠儿。而鸿蒙系统的崛起,更是为跨平台开发注入了新的活力。为了助力开发者在鸿蒙生态中快速实现 flutter_exit_app 退出应用程序功能,本文将深入浅出地为大家解析如何适配 flutter_exit_app 三方库至鸿蒙平台。
一、适配鸿蒙版 flutter_exit_app 三方库
(一)版本选择与仓库简介
我们先去 pub 上查看最新版本,发现目前 pub 上最新是 1.1.4,我们选择以 1.1.4 版本为基础进行适配。flutter_exit_app 是一个用于在 Flutter 应用中退出应用程序功能的插件,其 GitHub 仓库为 https://github.com/xang555/flutter_exit_app ,我们的目标是将这个插件适配到鸿蒙平台。
(二)引入背景与使用场景
在 OpenHarmony 北向生态的发展过程中,许多已经适配了 Flutter 的厂商在接入 OpenHarmony 时,都希望能够继续使用 FlutterToast 来实现通知功能。因此,我们提供了这个适配方案,采用插件化的适配器模式,帮助生态伙伴快速实现产品化。
本方案适用于已经支持 Flutter 框架的设备在移植到 OpenHarmony 系统过程中,作为一个备选方案。
(三)使用文档与插件库使用
适配 OpenHarmony 平台的详细使用指导可以参考:Flutter使用指导文档
在项目中使用该插件库时,只需在 pubspec.yaml
文件的 dependencies
中新增如下配置:
dependencies:
flutter_exit_app:
git:
url: "https://gitcode.com/nutpi/flutter_exit_app.git"
path: ""
然后在项目根目录运行 flutter pub get
,即可完成依赖添加
接下来是具体的适配过程。
二、适配过程详解
(一)准备工作
确保已经配置好了 Flutter 开发环境,具体可参考 Flutter 配置指南。同时,从 官方插件库 下载待适配的三方插件。本指导书, 以适配 fflutter_exit_app 为例
(二)插件目录结构
下载并解压插件后,我们会看到以下目录结构:
- lib :对接 Dart 端代码的入口,由此文件接收到参数后,通过 channel 将数据发送到原生端。
- android :安卓端代码实现目录。
- ios :iOS 原生端实现目录。
- example :一个依赖于该插件的 Flutter 应用程序,用于说明如何使用它。
- README.md :介绍包的文件。
- CHANGELOG.md :记录每个版本中的更改。
- LICENSE :包含软件包许可条款的文件。
(三)创建插件的鸿蒙模块
在插件目录下,打开 Terminal,执行以下命令来创建一个鸿蒙平台的 Flutter 模块:
flutter create . --template=plugin --platforms=ohos
步骤:
-
用vscode/trae打开刚刚下载好的插件。
-
打开Terminal,cd到插件目录下。
-
执行命令
flutter create . --template=plugin --platforms=ohos
创建一个ohos平台的flutter模块。
(四)在根目录下添加鸿蒙平台配置
在项目根目录的 pubspec.yaml
文件中,添加鸿蒙平台的相关配置:
name: flutter_exit_app
description: A flutter plugin provides the best way to exit the app doesn't call exit(0) in dart code.
version: 1.1.4
homepage: https://github.com/xang555/flutter_exit_app
environment:
sdk: ">=2.14.0 <4.0.0"
flutter: ">=2.5.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
lints: ^3.0.0
test:
mockito:
build_runner:
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# This section identifies this Flutter project as a plugin project.
# The 'pluginClass' and Android 'package' identifiers should not ordinarily
# be modified. They are used by the tooling to maintain consistency when
# adding or updating assets for this project.
plugin:
platforms:
android:
package: com.laoitdev.lib.exit.app.flutter_exit_app
pluginClass: FlutterExitAppPlugin
ios:
pluginClass: FlutterExitAppPlugin
ohos:
package: com.laoitdev.lib.exit.app.flutter_exit_app
pluginClass: FlutterExitAppPlugin
# To add assets to your plugin package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.dev/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# To add custom fonts to your plugin package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.dev/custom-fonts/#from-packages
(五)编写鸿蒙插件的原生 ETS 模块
1. 创建鸿蒙插件模块
使用 DevEco Studio 打开鸿蒙项目。
2. 修改相关配置文件
在 ohos
目录内的 oh-package.json5
文件中添加 libs/flutter.har
依赖,并创建 .gitignore
文件,添加以下内容以忽略 libs
目录:
/node_modules
/oh_modules
/local.properties
/.preview
/.idea
/build
/libs
*.har
/.cxx
/.test
/BuildProfile.ets
/oh-package-lock.json5
oh-package.json5
文件内容如下:
{
"name": "flutter_exit_app",
"version": "1.0.0",
"description": "flutter plugin provides the best way to exit the app doesn't call exit(0) in dart code.",
"main": "index.ets",
"author": "nutpi",
"license": "Apache-2.0",
"dependencies": {
"@ohos/flutter_ohos": "file:./har/flutter.har"
},
"modelVersion": "5.0.4"
}
在 ohos
目录下创建 index.ets
文件,导出配置:
import FlutterExitAppPlugin from './src/main/ets/components/plugin/FlutterExitAppPlugin';
export default FlutterExitAppPlugin;
3. 编写 ETS 代码
文件结构和代码逻辑可以参考安卓或 iOS 的实现,鸿蒙的 API 文档可以参考 :https://gitcode.com/openharmony-sig/flutter_packages/tree/master/packages/path_provider/path_provider_android
ohos的api可以参考:https://gitcode.com/openharmony/docs
以下是 FlutterExitAppPlugin.ets
文件的代码示例:
import {
FlutterPlugin,
FlutterPluginBinding,
MethodCall,
MethodCallHandler,
MethodChannel,
MethodResult,
} from '@ohos/flutter_ohos';
import { AbilityAware, AbilityPluginBinding } from '@ohos/flutter_ohos';
import {common, UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
/** FlutterExitAppPlugin **/
export default class FlutterExitAppPlugin implements FlutterPlugin, MethodCallHandler , AbilityAware {
private channel: MethodChannel | null = null;
private static _context: Context | null = null;
private static _uiContext: common.UIAbilityContext | null = null;
constructor() {
}
static get uiContext(): common.UIAbilityContext | null {
return FlutterExitAppPlugin._uiContext;
}
static get context(): common.Context | null {
return FlutterExitAppPlugin._context;
}
get uiContext(): common.UIAbilityContext | null {
return FlutterExitAppPlugin._uiContext;
}
getUniqueClassName(): string {
return "FlutterExitAppPlugin"
}
onAttachedToAbility(binding: AbilityPluginBinding): void {
FlutterExitAppPlugin._uiContext = binding.getAbility().context;
// Called when the plugin is attached to an Ability.
}
onDetachedFromAbility(): void {
// this._uiContext = null;
}
onAttachedToEngine(binding: FlutterPluginBinding): void {
this.channel = new MethodChannel(binding.getBinaryMessenger(), "flutter_exit_app");
this.channel.setMethodCallHandler(this)
}
onDetachedFromEngine(binding: FlutterPluginBinding): void {
if (this.channel != null) {
this.channel.setMethodCallHandler(null)
}
}
onMethodCall(call: MethodCall, result: MethodResult): void {
if (call.method == "getPlatformVersion") {
result.success("OpenHarmony ^ ^ ")
} else if (call.method == "com.laoitdev.exit.app") {
console.info("hhhhhhhhhh")
if (FlutterExitAppPlugin._uiContext) { // Add null check here
try {
FlutterExitAppPlugin._uiContext.terminateSelf()
.then(() => {
// 执行正常业务
console.info('terminateSelf succeed');
result.success("Done"); // Inform Flutter about success
})
.catch((err: BusinessError) => {
// 处理业务逻辑错误
console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
result.error("TERMINATE_FAILED", `terminateSelf failed: ${err.message}`, null);
});
} catch (err) {
// 捕获同步的参数错误
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
result.error("TERMINATE_ERROR", `terminateSelf error: ${message}`, null);
}
} else {
console.error("UIContext is null, cannot terminate self.");
result.error("CONTEXT_NULL", "UIContext is null", null); // Inform Flutter about the error
}
} else {
result.notImplemented()
}
}
}
现在就可以正常使用啦。
这里我主要参考的是
4.UIAbilityContext.terminateSelf
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
try {
this.context.terminateSelf()
.then(() => {
// 执行正常业务
console.info('terminateSelf succeed');
})
.catch((err: BusinessError) => {
// 处理业务逻辑错误
console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// 捕获同步的参数错误
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
}
}
}
三、关于鸿蒙版Flutter的 context
这里我使用的是UIAbilityContext
UIAbilityContext
插件继承 AbilityAware
并且在 onAttachedToAbility
方法中获取。
export default class XXXPlugin implements FlutterPlugin, MethodCallHandler, AbilityAware {
private _uiContext: common.UIAbilityContext | null = null;
onAttachedToAbility(binding: AbilityPluginBinding): void {
this.XXXPlugin = binding.getAbility().context;
}
onDetachedFromAbility(): void {
this.XXXPlugin = null;
}
}
该 uiContext
可以用于获取 applicationInfo
等属性。以及退出等操作。还有另外一种是
ApplicationContex
你可以直接从 onAttachedToEngine
方法中获取。
private context: Context | null = null;
onAttachedToEngine(binding: FlutterPluginBinding): void {
this.context = binding.getApplicationContext();
}
onDetachedFromEngine(binding: FlutterPluginBinding): void {
this.context = null;
}
该 context
可以用于获取 applicationInfo
等属性。
let applicationInfo = this.context.applicationInfo;
四、编写 Example
1. 创建 Example 应用
在插件根目录下创建一个名为 example
的文件夹,用于存放示例应用。在 example
文件夹中,创建一个鸿蒙平台的 Flutter 应用,用于验证插件功能。
2. 签名与运行
使用 Deveco Studio
打开 example > ohos
目录,单击 File > Project Structure > Project > Signing Configs
,勾选 Automatically generate signature
,等待自动签名完成。然后运行以下命令:
flutter pub get
flutter build hap --debug
如果应用正常启动,说明插件适配成功。如果没有,欢迎大家联系坚果派一起支持。
五、总结
通过以上步骤,我们成功地将 flutter_exit_app 三方库适配到了鸿蒙平台。这个过程涉及到了解插件的基本信息、配置开发环境、创建鸿蒙模块、编写原生代码以及测试验证等多个环节。希望这篇博客能够帮助到需要进行 flutter_exit_app 鸿蒙适配的开发者们,让大家在鸿蒙生态的开发中更加得心应手。
六、参考
- [如何使用Flutter与OpenHarmony通信 FlutterChannel](https://gitcode.com/openharmony-sig/flutter_samples/blob/master/ohos/docs/04_development/如何使用Flutter与OpenHarmony通信 FlutterChannel.md)
- [开发module](https://gitcode.com/openharmony-sig/flutter_samples/blob/master/ohos/docs/04_development/如何使用混合开发 module.md)
- 开发package
- 开发plugin
- [开发FFI plugin](https://gitcode.com/openharmony-sig/flutter_samples/blob/master/ohos/docs/04_development/开发FFI plugin.md)
- developing-packages
七、坚果派
坚果派由坚果等人创建,团队拥有若干华为HDE,以及若干其他领域的三十余位万粉博主运营。专注于分享的技术包括HarmonyOS/OpenHarmony,ArkUI-X,元服务,服务卡片,华为自研语言,BlueOS操作系统、团队成员聚集在北京、上海、广州、深圳、南京、杭州、苏州、宁夏等地。 聚焦“鸿蒙原生应用”、“智能物联”和“AI赋能”、“人工智能”四大业务领域,依托华为开发者专家等强大的技术团队,以及涵盖需求、开发、测试、运维于一体的综合服务体系,赋能文旅、媒体、社交、家居、消费电子等行业客户,满足社区客户数字化升级转型的需求,帮助客户实现价值提升。 目前上架鸿蒙原生应用18款,三方库72个。
- 17回答
- 20粉丝
- 11关注
- Flutter_udid 三方库鸿蒙适配之旅:从零到一的深度实践
- FlutterToast 三方库鸿蒙适配之旅:从零到一的深度实践
- 从零到一:flutter_timezone库的鸿蒙适配深度探索
- Flutter到鸿蒙的跨越:torch_light库的鸿蒙适配之旅
- Flutter到鸿蒙的跨越:flutter_native_contact_picker库的鸿蒙适配之旅
- Flutter到鸿蒙的跨越:flutter_native_contact_picker库的鸿蒙适配之旅
- 上传PR到第三方库可能遇到的问题
- 如何发布第三方库到 OpenHarmony,并提交一个PR
- img-type三方库
- 常用的ArkTS第三方库
- 给 OpenHarmony 三方库添加徽章
- OpenHarmony三方库使用指南
- 最受欢迎的三方库之SpinKit
- 开源第三方库资源汇总
- 鸿蒙Flutter实战:05-使用第三方插件