HarmonyOS之UIAbilityContext详解
UIAbilityContext
是 HarmonyOS Stage 模型下,UI Ability的上下文对象,继承了基础 AbilityContext
,是操作界面能力的关键对象,负责管理能力运行环境和系统资源接口。
1. 启动 Ability
通过 startAbility
启动新的页面或服务能力。
this.context.startAbility({bundleName: 'com.example.app',abilityName: 'com.example.app.MainAbility',parameters: { userId: 1001 }
});
2. 结束当前 Ability
关闭当前 Ability(相当于页面关闭或服务停止)。
this.context.terminateSelf();
3. 事件总线:事件注册、发送、注销
eventHub
是内置事件总线,支持事件的发布与订阅。
注册事件
const callback = (data) => {console.log('事件回调收到数据:', data);
};
this.context.eventHub.on('customEvent', callback);
触发事件
this.context.eventHub.emit('customEvent', { msg: 'hello world' });
注销事件
this.context.eventHub.off('customEvent', callback);
4. 获取 Ability 信息
访问当前 Ability 相关的元信息。
console.log('包名:', this.context.bundleName);
console.log('能力名:', this.context.abilityName);
5. 申请权限
申请系统权限,支持回调结果处理。
this.context.requestPermissionsFromUser(['ohos.permission.LOCATION'], (granted) => {if (granted) {console.log('权限申请成功');} else {console.log('权限申请失败');}
});
6. 获取文件系统目录路径
获取应用私有目录、缓存目录等路径。
console.log('应用私有目录:', this.context.getFilesDir());
console.log('缓存目录:', this.context.getCacheDir());
7. 发送系统通知
创建并发送通知给用户。
this.context.sendNotification({content: {contentType: 1,title: '通知标题',text: '通知内容'}
});
8. 访问资源管理
通过资源 ID 获取字符串、图片等资源。
const myString = this.context.getResourceManager().getString('app_name');
console.log('应用名称:', myString);
9. 注册生命周期回调
监听当前 Ability 的生命周期变化。
this.context.on('foreground', () => {console.log('Ability进入前台');
});this.context.on('background', () => {console.log('Ability进入后台');
});
综合示例:UIAbilityContext的常用操作
export default class MyAbility extends UIAbility {onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {console.log('Ability启动,包名:', this.context.bundleName);// 启动另一个能力this.context.startAbility({bundleName: 'com.example.other',abilityName: 'com.example.other.MainAbility',parameters: { from: 'MyAbility' }});// 监听自定义事件this.context.eventHub.on('refreshData', (data) => {console.log('收到刷新数据事件:', data);});// 申请权限this.context.requestPermissionsFromUser(['ohos.permission.LOCATION'], (granted) => {if (granted) {console.log('位置权限已授予');}});// 发送通知this.context.sendNotification({content: {contentType: 1,title: '欢迎',text: 'Hello HarmonyOS'}});// 监听生命周期事件this.context.on('foreground', () => {console.log('Ability进入前台');});}
}
总结
功能 | 作用说明 | 代码示例关键字 |
---|---|---|
启动 Ability | 跳转页面或启动后台服务 | this.context.startAbility() |
结束 Ability | 关闭当前能力 | this.context.terminateSelf() |
事件通信 | 事件注册、触发、注销 | this.context.eventHub.on/emit/off |
权限申请 | 请求系统权限 | this.context.requestPermissionsFromUser() |
目录访问 | 获取应用私有目录、缓存目录 | this.context.getFilesDir() |
发送通知 | 给用户发送通知 | this.context.sendNotification() |
资源管理 | 访问字符串、图片等资源 | this.context.getResourceManager().getString() |
生命周期监听 | 监听前后台切换 | this.context.on('foreground'/'background') |