1# 创建PageAbility 2 3 4通过DevEco Studio开发平台创建PageAbility时,DevEco Studio会在app.js/app.ets中默认生成onCreate()和onDestroy()方法,其他方法需要开发者自行实现。接口说明参见前述章节,创建PageAbility示例如下: 5 6```ts 7import featureAbility from '@ohos.ability.featureAbility'; 8import hilog from '@ohos.hilog'; 9 10const TAG: string = 'MainAbility'; 11const domain: number = 0xFF00; 12 13class MainAbility { 14 onCreate() { 15 // 获取context并调用相关方法 16 let context = featureAbility.getContext(); 17 context.getBundleName((data, bundleName) => { 18 hilog.info(domain, TAG, 'ability bundleName:' ,bundleName); 19 }); 20 hilog.info(domain, TAG, 'Application onCreate'); 21 } 22 23 onDestroy() { 24 hilog.info(domain, TAG, 'Application onDestroy'); 25 } 26 27 onShow(): void { 28 hilog.info(domain, TAG, 'Application onShow'); 29 } 30 31 onHide(): void { 32 hilog.info(domain, TAG, 'Application onHide'); 33 } 34 35 onActive(): void { 36 hilog.info(domain, TAG, 'Application onActive'); 37 } 38 39 onInactive(): void { 40 hilog.info(domain, TAG, 'Application onInactive'); 41 } 42 43 onNewWant() { 44 hilog.info(domain, TAG, 'Application onNewWant'); 45 } 46} 47 48export default new MainAbility(); 49``` 50 51 52PageAbility创建成功后,其abilities相关的配置项在config.json中体现,一个名字为EntryAbility的config.json配置文件示例如下: 53 54```json 55{ 56 ... 57 "module": { 58 ... 59 "abilities": [ 60 { 61 "skills": [ 62 { 63 "entities": [ 64 "entity.system.home" 65 ], 66 "actions": [ 67 "action.system.home" 68 ] 69 } 70 ], 71 "orientation": "unspecified", 72 "formsEnabled": false, 73 "name": ".MainAbility", 74 "srcLanguage": "ets", 75 "srcPath": "MainAbility", 76 "icon": "$media:icon", 77 "description": "$string:MainAbility_desc", 78 "label": "$string:MainAbility_label", 79 "type": "page", 80 "visible": true, 81 "launchType": "singleton" 82 }, 83 ... 84 ] 85 ... 86 } 87} 88``` 89 90 91FA模型中,可以通过featureAbility的getContext接口获取应用上下文,进而使用上下文提供的能力。 92 93 94 **表1** featureAbility接口说明 95 96| 接口名 | 接口描述 | 97| -------- | -------- | 98| getContext() | 获取应用上下文。 | 99 100 101通过getContext获取应用上下文并获取分布式目录的示例如下: 102 103```ts 104import featureAbility from '@ohos.ability.featureAbility'; 105import fs from '@ohos.file.fs'; 106import promptAction from '@ohos.promptAction'; 107import hilog from '@ohos.hilog'; 108 109const TAG: string = 'PagePageAbilityFirst'; 110const domain: number = 0xFF00; 111``` 112```ts 113(async (): Promise<void> => { 114 let dir: string; 115 try { 116 hilog.info(domain, TAG, 'Begin to getOrCreateDistributedDir'); 117 dir = await featureAbility.getContext().getOrCreateDistributedDir(); 118 promptAction.showToast({ 119 message: dir 120 }); 121 hilog.info(domain, TAG, 'distribute dir is ' + dir); 122 let fd: number; 123 let path = dir + '/a.txt'; 124 fd = fs.openSync(path, fs.OpenMode.READ_WRITE).fd; 125 fs.close(fd); 126 } catch (error) { 127 hilog.error(domain, TAG, 'getOrCreateDistributedDir failed with : ' + error); 128 } 129})() 130``` 131