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