@capacitortest/capacitor-app
v8.0.0
Published
The App API handles high level App state and events. For example, this API emits events when the app enters and leaves the foreground, handles deeplinks, opens other apps, and manages persisted plugin state.
Readme
@capacitor/[email protected]
@capacitor/app 是Capacitor生态系统中的核心插件,App的API提供了处理高级应用状态与事件的功能。为跨平台应用开发提供设备差异化适配能力,本文档仅说明在OpenHarmony环境下的使用情况。
插件简介
@capacitor/app 提供了高层级的应用状态与事件如pause、resume等
安装指南
方式一:手动引入安装
根据插件源码中 plugin.xml 配置在项目中添加/修改相关配置
- 根据
plugin.xml的config-json项,找到entry模块中capacitor.plugins.json文件,并根据param标签添加配置。[ { "pkg": "@capacitor/app", "classpath": "App" } ] - 根据
plugin.xml的CMakeLists项,找到capacitor模块,路径为target字段的文件CMakeLists.txt,添加add_subdirectory,同时添加target_link_libraries。add_subdirectory(App) // ... 注意需添加在-Wl,--whole-archive 和 -Wl,--no-whole-archive之间 target_link_libraries(capacitor PUBLIC // ... "-Wl,--whole-archive" App "-Wl,--no-whole-archive" // ... ) - 根据
plugin.xml的source-file项,将src字段的路径代码复制到capacitor模块中target-dir字段的目录中。将源码中src/main/cpp/App目录下的App.h、App.cpp、CMakeLists.txt文件文件引入到capacitor模块中src/main/cpp/App目录下 将源码中src/main/ets/components/App目录下的App.ets文件引入到capacitor模块中src/main/ets/components/App目录下 - 在
capacitor模块的build-profile.json5文件中,buildOption/arkOptions/runtimeOnly/sources配置项数组中加入步骤3中拷贝的ets文件路径:"buildOption": { // ... "arkOptions": { "runtimeOnly":[ // ... "./src/main/ets/components/App/App.ets" // ... ] } }
方式二:通过 HCapacitor CLI 安装
待后续开源,该方式会取代方式一 在 Capacitor 项目根目录执行以下命令,自动下载并集成插件:
安装hcionic
npm install -g hionic安装最新稳定版
hionic plugin add @capacitor/app
指定平台安装
hionic plugin add @capacitor/app --platform ohos
指定平台卸载
hionic plugin remove @capacitor/app --platform ohos配置
以下配置可用
| 数据 | 类型 | 描述 |
|--------------------------------|----------------------|-----------------|
| disableBackButtonHandler | boolean | 禁用插件的默认返回按钮处理功能 |
示例
capacitor.config.json
载于:capacitor.config.json
{
"plugins": {
"App": {
"disableBackButtonHandler": true
}
}
}核心 API:
接口方法
| 方法名 | 返回类型 | 描述 |
|--------------------------------------------------------------------|---------------------------------|------------------------------------|
| exitApp() | Promise<void> | 强制退出应用。 |
| getInfo() | Promise<AppInfo> | 返回与应用相关的信息。 |
| getState() | Promise<AppState> | 获取当前应用状态。 |
| getLaunchUrl() | Promise<AppLaunchUrl> | 获取启动应用时传入的 URL(如果有)。 |
| minimizeApp() | Promise<void> | 将应用程序最小化。 |
| toggleBackButtonHandler(options: ToggleBackButtonHandlerOptions) | Promise<void> | 在运行时启用或禁用插件的返回按钮处理。 |
| addListener('appStateChange', ...) | Promise<PluginListenerHandle> | 监听应用的状态的变化。 |
| addListener('pause', ...) | Promise<PluginListenerHandle> | 监听应用被暂停的事件。 |
| addListener('resume', ...) | Promise<PluginListenerHandle> | 监听应用被恢复的事件。 |
| addListener('appUrlOpen', ...) | Promise<PluginListenerHandle> | 监听应用的URL打开事件。 |
| addListener('appRestoredResult', ...) | Promise<PluginListenerHandle> | 不支持。 |
| addListener('backButton', ...) | Promise<PluginListenerHandle> | 监听硬件返回按钮事件。一旦监听了此事件,默认的返回按钮行为将被禁用。 |
| removeAllListeners() | Promise<void> | 移除该插件的所有原生监听器。 |
数据结构`
AppInfo
| Prop | Type | Description |
| ------------ | -------- | ------------------------------------------------------------ |
| name | string | 应用的名称。 |
| id | string | 应用的标识符。 |
| build | string | 构建版本。 |
| version| string | 应用版本号。 |
AppState
| Prop | Type | Description |
| ------------ | -------- | ---------------------------------------------------------- |
| isActive| boolean| 应用是否处于活跃状态。 |
AppLaunchUrl
| Prop | Type | Description |
| ------------ | -------- | ------------------------------------------------------------ |
| url |string | 用于打开应用的 URL。 |
ToggleBackButtonHandlerOptions
| Prop | Type | Description |
| ------------ | -------- | ------------------------------------------------------------ |
| enabled | boolean| 指示是否启用或禁用默认的返回按钮处理。 |
PluginListenerHandle
| Prop | Type |
| ------------ | ---------------------- |
| remove | () => Promise<void> |
URLOpenListenerEvent
| Prop | Type | Description |
| ---------------------------- | ---------------------- | ------------------------------------------------------------ |
| url | string | 应用被打开时使用的 URL。 |
使用示例
基础示例1:获取应用信息
import { App } from '@capacitor/app';
const handleGetInfo = async () => {
try {
// 使用Capacitor App插件获取应用信息
const result = await App.getInfo();
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('get-info', {
status: 'success',
data: result
});
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('get-info', {
status: 'error',
message: `获取应用信息失败: ${errorMsg}`
});
}
console.error('获取应用信息失败:', error);
}
};
基础示例2:获取应用的当前状态
const handleGetState = async () => {
try {
// 使用Capacitor App插件获取应用状态
const result = await App.getState();
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('get-state', {
status: 'success',
data: result
});
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('get-state', {
status: 'error',
message: `获取应用状态失败: ${errorMsg}`
});
}
console.error('获取应用状态失败:', error);
}
};
基础示例3:获取应用启动时的url
const handleGetLaunchUrl = async () => {
try {
// 使用Capacitor App插件获取应用启动URL
const result = await App.getLaunchUrl();
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('get-launch-url', {
status: 'success',
data: result || { message: '未获取到启动URL' }
});
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('get-launch-url', {
status: 'error',
message: `获取应用启动URL失败: ${errorMsg}`
});
}
console.error('获取应用启动URL失败:', error);
}
};
基础示例3:使app最小化
const handleMinimizeApp = async () => {
try {
// 使用Capacitor App插件最小化应用
await App.minimizeApp();
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('minimize-app', {
status: 'success',
message: '应用已最小化(仅Android支持)'
});
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('minimize-app', {
status: 'error',
message: `最小化应用失败(仅Android支持): ${errorMsg}`
});
}
console.error('最小化应用失败:', error);
}
};
基础示例5:移除App插件的所有事件监听
const handleRemoveAllListeners = async () => {
try {
// 使用Capacitor App插件移除所有监听器
await App.removeAllListeners();
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('remove-listeners', {
status: 'success',
message: '已移除所有应用事件监听器'
});
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('remove-listeners', {
status: 'error',
message: `移除监听器失败: ${errorMsg}`
});
}
console.error('移除监听器失败:', error);
}
};
基础示例6:事件监听处理函数
const handleAddPauseListener = async () => {
try {
// 添加应用暂停监听器
const listener = await App.addListener('pause', () => {
console.log('应用已暂停');
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('listener-pause', {
status: 'success',
message: '监听到:应用已进入后台'
});
}
});
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('listener-pause', {
status: 'success',
message: '已添加应用暂停监听器'
});
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
if (apiButtonSectionRef.value) {
apiButtonSectionRef.value.updateButtonResult('listener-pause', {
status: 'error',
message: `添加监听器失败: ${errorMsg}`
});
}
console.error('添加应用暂停监听器失败:', error);
}
};
该插件获取启动URL需在EntryAbility里注册getLaunchUrl方法
PluginRegisterHandle(this,want,"/App/App","getLaunchUrl","")
参考资料
- Android、ios插件说明:www.npmjs.com
许可证
本项目遵循 MIT License
