适配仓库地址[1]
#鸿蒙坚果派 #鸿蒙版Flutter #鸿蒙开发者 #Flutter三方库
在数字化浪潮的推动下,跨平台开发框架如 Flutter 凭借其高效、便捷的特性,成为了开发者们的宠儿。而鸿蒙系统的崛起,更是为跨平台开发注入了新的活力。为了助力开发者在鸿蒙生态中快速实现 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 使用指导文档[2]
在项目中使用该插件库时,只需在 pubspec.yaml
文件的 dependencies
中新增如下配置:
dependencies:
flutter_exit_app:
git:
url: "https://gitcode.com/nutpi/flutter_exit_app.git"
path: ""
然后在项目根目录运行 flutter pub get
,即可完成依赖添加
接下来是具体的适配过程。
确保已经配置好了 Flutter 开发环境,具体可参考 Flutter 配置指南[3]。同时,从 官方插件库[4] 下载待适配的三方插件。本指导书, 以适配 fflutter_exit_app[5] 为例
image-20250417200546042
下载并解压插件后,我们会看到以下目录结构:
在插件目录下,打开 Terminal,执行以下命令来创建一个鸿蒙平台的 Flutter 模块:
flutter create . --template=plugin --platforms=ohos
步骤:
flutter create . --template=plugin --platforms=ohos
创建一个 ohos 平台的 flutter 模块。在项目根目录的 pubspec.yaml
文件中,添加鸿蒙平台的相关配置:
name: flutter_exit_app
description:Aflutterpluginprovidesthebestwaytoexittheappdoesn'tcallexit(0)indartcode.
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
使用 DevEco Studio 打开鸿蒙项目。
在 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;
文件结构和代码逻辑可以参考安卓或 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 **/
exportdefaultclass FlutterExitAppPlugin implements FlutterPlugin, MethodCallHandler , AbilityAware {
private channel: MethodChannel | null = null;
private static _context: Context | null = null;
private static _uiContext: common.UIAbilityContext | null = null;
constructor() {
}
staticget uiContext(): common.UIAbilityContext | null {
return FlutterExitAppPlugin._uiContext;
}
staticget 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 ^ ^ ")
} elseif (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()
}
}
}
现在就可以正常使用啦。
这里我主要参考的是
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}`);
}
}
}
参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-inner-application-uiabilitycontext#uiabilitycontextterminateself-1
这里我使用的是 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
等属性。以及退出等操作。还有另外一种是
你可以直接从 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
的文件夹,用于存放示例应用。在 example
文件夹中,创建一个鸿蒙平台的 Flutter 应用,用于验证插件功能。
使用 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 鸿蒙适配的开发者们,让大家在鸿蒙生态的开发中更加得心应手。
参考资料
[1]
适配仓库地址: https://gitcode.com/nutpi/flutter_exit_app
[2]
Flutter 使用指导文档: https://gitcode.com/openharmony-sig/flutter_samples/blob/master/ohos/docs/07_plugin/ohos%E5%B9%B3%E5%8F%B0%E9%80%82%E9%85%8Dflutter%E4%B8%89%E6%96%B9%E5%BA%93%E6%8C%87%E5%AF%BC.md
[3]
Flutter 配置指南: https://gitcode.com/openharmony-sig/flutter_flutter/blob/master/README.md
[4]
官方插件库: https://pub.dev/
[5]
fflutter_exit_app: https://pub-web.flutter-io.cn/packages/flutter_exit_app/versions/1.1.4
[6]
开发 package: https://gitcode.com/openharmony-sig/flutter_samples/blob/master/ohos/docs/04_development/开发package.md
[7]
开发 plugin: https://gitcode.com/openharmony-sig/flutter_samples/blob/master/ohos/docs/04_development/开发plugin.md
[8]
developing-packages: https://docs.flutter.cn/packages-and-plugins/developing-packages
[9]
适配仓库地址: https://gitcode.com/nutpi/flutter_exit_app
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有