
回复
作为一个曾在后台服务开发中手忙脚乱的开发者,今天要揭秘HarmonyOS的ExtensionAbility!第一次用它做后台服务时,同事以为我开了「后台挂」,其实只是用对了这个隐藏的能力扩展神器~
想象一场演唱会:
类型 | 职责 | 生活类比 |
---|---|---|
ServiceExtensionAbility | 后台服务,如音乐播放、文件下载 | 后台乐队 |
FormExtensionAbility | 服务卡片,如天气卡片 | 演唱会节目单 |
InputMethodExtensionAbility | 输入法扩展 | 提词器 |
阶段 | 类比场景 | 典型操作 |
---|---|---|
onCreate | 团队开工准备 | 初始化服务、加载配置 |
onForeground | 团队进入工作状态 | 开始处理任务、申请资源 |
onBackground | 团队暂停工作 | 释放非必要资源、保存进度 |
onDestroy | 团队收工离场 | 销毁实例、清理内存 |
import { ServiceExtensionAbility } from '@ohos.app.ability';
export default class MusicService extends ServiceExtensionAbility {
onCreate(want) {
console.log('音乐团队开工(服务初始化)');
this.initMusicPlayer(); // 初始化播放器
}
onForeground() {
console.log('音乐团队开始工作(服务启动)');
this.startPlayback(); // 开始播放音乐
}
onBackground() {
console.log('音乐团队暂停(服务后台)');
this.pausePlayback(); // 暂停播放
}
onDestroy() {
console.log('音乐团队收工(服务销毁)');
this.releasePlayer(); // 释放资源
}
}
// 下载服务实现
import { ServiceExtensionAbility } from '@ohos.app.ability';
export default class DownloadService extends ServiceExtensionAbility {
private downloadManager: DownloadManager;
onCreate() {
this.downloadManager = new DownloadManager();
console.log('下载服务启动');
}
onRequest(want, startId) {
// 接收下载请求
const url = want.parameters?.url;
if (url) {
this.downloadManager.startDownload(url);
}
}
onDestroy() {
this.downloadManager.stopAll();
console.log('下载服务停止');
}
}
// 前台调用下载服务
const want = {
bundleName: 'com.example.downloader',
abilityName: 'DownloadService'
};
this.context.startAbility(want);
// 后台服务发消息给前台
import { getContext } from '@ohos.app.ability';
const eventHub = getContext(this).eventHub;
eventHub.publish('downloadProgress', { progress: 50 });
// 前台UIAbility收消息
eventHub.on('downloadProgress', (data) => {
this.downloadProgress = data.progress; // 更新进度条
});
// 天气卡片扩展
import { FormExtensionAbility } from '@ohos.app.ability';
export default class WeatherForm extends FormExtensionAbility {
onShow() {
console.log('天气卡片显示');
this.updateWeatherData(); // 更新天气数据
}
onUpdate(formId) {
console.log(`天气卡片更新,ID: ${formId}`);
this.refreshWeather(formId); // 刷新卡片数据
}
onDestroy() {
console.log('天气卡片销毁');
}
}
// 卡片配置(config.json)
{
"extensionAbilities": [
{
"name": ".WeatherForm",
"src": ["WeatherForm.ts"],
"form": {
"formName": "天气卡片",
"supportDimensions": ["4*2"]
}
}
]
}
// 卡片UI(ArkUI)
@Entry
@Component
struct WeatherForm {
@State weather: WeatherData = { temp: '25℃', condition: '晴' };
build() {
Column {
Text('今日天气')
.fontSize(16)
.margin({ bottom: 5 })
Text(`${this.weather.temp} ${this.weather.condition}`)
.fontSize(24)
.fontWeight(FontWeight.Bold)
}
.width('100%')
.height('100%')
.padding(10)
.backgroundColor(Color.White)
}
}
// module.json5中配置
{
"extensionAbilities": [
{
"name": ".SecureService",
"src": ["SecureService.ts"],
"sandbox": {
"enabled": true, // 开启沙箱
"permissions": ["ohos.permission.READ_WEATHER"] // 沙箱内权限
}
}
]
}
场景 | 传统后台开发 | ExtensionAbility开发 |
---|---|---|
后台服务稳定性 | 一个崩溃全APP挂 | 独立沙箱不影响前台 |
卡片更新效率 | 需打开APP才更新 | 后台自动刷新卡片 |
权限安全性 | 权限混乱易泄漏 | 沙箱隔离更安全 |
onBackground() {
// 释放非必要资源,像团队暂停时收起工具
this.releaseUnusedResources();
// 后台任务轻量化,像团队轻装待命
this.lightweightMode();
}
第一次用ExtensionAbility做音乐后台时,前台切歌后台不卡顿,同事以为我用了什么黑科技~ 其实只是用对了沙箱隔离和后台服务优化~