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