From ce7f94d60623e57c67aaf18d3a53d93cca75aab7 Mon Sep 17 00:00:00 2001 From: liuliu <liuliu40@huawei.com> Date: Wed, 30 Aug 2023 11:28:44 +0800 Subject: [PATCH] update Signed-off-by: liuliu <liuliu40@huawei.com> Change-Id: I29c06ef43142bb46f1f828c1135d74b0528bd7a6 --- zh-cn/application-dev/IDL/idl-guidelines.md | 60 ++++++++------- .../application-models/access-dataability.md | 64 ++++++++++++++-- .../application-models/api-switch-overview.md | 2 +- .../application-context-fa.md | 2 + .../application-context-stage.md | 2 +- .../bind-serviceability-from-stage.md | 2 +- .../application-models/create-dataability.md | 75 +++++++++++-------- .../application-models/create-pageability.md | 27 ++++--- .../create-serviceability.md | 18 ++--- .../hop-multi-device-collaboration.md | 3 - .../inputmethodextentionability.md | 6 +- .../application-models/itc-with-worker.md | 2 +- .../mission-management-overview.md | 2 +- .../serviceextensionability.md | 11 +-- .../application-models/start-page.md | 59 +++++++++++---- .../uiability-data-sync-with-ui.md | 2 +- .../uiability-intra-device-interaction.md | 66 +++++++++++----- .../uiability-launch-type.md | 4 +- .../application-models/uiability-lifecycle.md | 11 ++- 19 files changed, 274 insertions(+), 144 deletions(-) diff --git a/zh-cn/application-dev/IDL/idl-guidelines.md b/zh-cn/application-dev/IDL/idl-guidelines.md index f8ae1b0233..655734d746 100644 --- a/zh-cn/application-dev/IDL/idl-guidelines.md +++ b/zh-cn/application-dev/IDL/idl-guidelines.md @@ -215,11 +215,12 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl super(des); } - async onRemoteMessageRequest(code: number, data, reply, option): Promise<boolean> { + async onRemoteMessageRequest(code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence, + option: rpc.MessageOption): Promise<boolean> { console.log("onRemoteMessageRequest called, code = " + code); if (code == IdlTestServiceStub.COMMAND_TEST_INT_TRANSACTION) { let _data = data.readInt(); - this.testIntTransaction(_data, (errCode, returnValue) => { + this.testIntTransaction(_data, (errCode: number, returnValue: number) => { reply.writeInt(errCode); if (errCode == 0) { reply.writeInt(returnValue); @@ -228,7 +229,7 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl return true; } else if (code == IdlTestServiceStub.COMMAND_TEST_STRING_TRANSACTION) { let _data = data.readString(); - this.testStringTransaction(_data, (errCode) => { + this.testStringTransaction(_data, (errCode: number) => { reply.writeInt(errCode); }); return true; @@ -240,13 +241,13 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl let value = data.readInt(); _data.set(key, value); } - this.testMapTransaction(_data, (errCode) => { + this.testMapTransaction(_data, (errCode: number) => { reply.writeInt(errCode); }); return true; } else if (code == IdlTestServiceStub.COMMAND_TEST_ARRAY_TRANSACTION) { let _data = data.readStringArray(); - this.testArrayTransaction(_data, (errCode, returnValue) => { + this.testArrayTransaction(_data, (errCode: number, returnValue: number) => { reply.writeInt(errCode); if (errCode == 0) { reply.writeInt(returnValue); @@ -305,17 +306,20 @@ class IdlTestImp extends IdlTestServiceStub { 在æœåŠ¡å®žçŽ°æŽ¥å£åŽï¼Œéœ€è¦å‘客户端公开该接å£ï¼Œä»¥ä¾¿å®¢æˆ·ç«¯è¿›ç¨‹ç»‘定。如果开å‘者的æœåŠ¡è¦å…¬å¼€è¯¥æŽ¥å£ï¼Œè¯·æ‰©å±•Ability并实现onConnect()从而返回IRemoteObject,以便客户端能与æœåŠ¡è¿›ç¨‹äº¤äº’。æœåŠ¡ç«¯å‘客户端公开IRemoteAbility接å£çš„代ç 示例如下: ```ts -export default { +import Want from '@ohos.app.ability.Want'; +import rpc from "@ohos.rpc"; + +export default class ServiceAbility { onStart() { console.info('ServiceAbility onStart'); - }, + }; onStop() { console.info('ServiceAbility onStop'); - }, - onCommand(want, startId) { + }; + onCommand(want: Want, startId: number) { console.info('ServiceAbility onCommand'); - }, - onConnect(want) { + }; + onConnect(want: Want) { console.info('ServiceAbility onConnect'); try { console.log('ServiceAbility want:' + typeof(want)); @@ -325,9 +329,9 @@ export default { console.log('ServiceAbility error:' + err) } console.info('ServiceAbility onConnect end'); - return new IdlTestImp('connect'); - }, - onDisconnect(want) { + return new IdlTestImp('connect') as rpc.RemoteObject; + }; + onDisconnect(want: Want) { console.info('ServiceAbility onDisconnect'); console.info('ServiceAbility want:' + JSON.stringify(want)); } @@ -339,6 +343,8 @@ export default { 客户端调用connectServiceExtensionAbility()以连接æœåŠ¡æ—¶ï¼Œå®¢æˆ·ç«¯çš„onAbilityConnectDoneä¸çš„onConnect回调会接收æœåŠ¡çš„onConnect()方法返回的IRemoteObject实例。由于客户端和æœåŠ¡åœ¨ä¸åŒåº”用内,所以客户端应用的目录内必须包å«.idl文件(SDK工具会自动生æˆProxy代ç†ç±»)的副本。客户端的onAbilityConnectDoneä¸çš„onConnect回调会接收æœåŠ¡çš„onConnect()方法返回的IRemoteObject实例,使用IRemoteObject创建IdlTestServiceProxy类的实例对象testProxy,然åŽè°ƒç”¨ç›¸å…³IPC方法。示例代ç 如下: ```ts +import common from '@ohos.app.ability.common'; +import Want from '@ohos.app.ability.Want'; import IdlTestServiceProxy from './idl_test_service_proxy' function callbackTestIntTransaction(result: number, ret: number): void { @@ -365,10 +371,10 @@ function callbackTestArrayTransaction(result: number, ret: number): void { } } -let onAbilityConnectDone = { - onConnect:function (elementName, proxy) { - let testProxy = new IdlTestServiceProxy(proxy); - let testMap = new Map(); +let onAbilityConnectDone: common.ConnectOptions = { + onConnect: (elementName, proxy) => { + let testProxy: IdlTestServiceProxy = new IdlTestServiceProxy(proxy); + let testMap: Map<number, number> = new Map(); testMap.set(1, 1); testMap.set(1, 2); testProxy.testIntTransaction(123, callbackTestIntTransaction); @@ -376,21 +382,23 @@ let onAbilityConnectDone = { testProxy.testMapTransaction(testMap, callbackTestMapTransaction); testProxy.testArrayTransaction(['1','2'], callbackTestMapTransaction); }, - onDisconnect:function (elementName) { + onDisconnect: (elementName) => { console.log('onDisconnectService onDisconnect'); }, - onFailed:function (code) { + onFailed: (code) => { console.log('onDisconnectService onFailed'); } }; +let context: common.UIAbilityContext = this.context; + function connectAbility(): void { - let want = { + let want: Want = { bundleName: 'com.example.myapplicationidl', abilityName: 'com.example.myapplicationidl.ServiceAbility' }; let connectionId = -1; - connectionId = this.context.connectServiceExtensionAbility(want, onAbilityConnectDone); + connectionId = context.connectServiceExtensionAbility(want, onAbilityConnectDone); } @@ -420,18 +428,18 @@ export default class MySequenceable { getString() : string { return this.str; } - marshalling(messageParcel) { + marshalling(messageParcel: rpc.MessageSequence) { messageParcel.writeInt(this.num); messageParcel.writeString(this.str); return true; } - unmarshalling(messageParcel) { + unmarshalling(messageParcel: rpc.MessageSequence) { this.num = messageParcel.readInt(); this.str = messageParcel.readString(); return true; } - private num; - private str; + private num: number; + private str: string; } ``` diff --git a/zh-cn/application-dev/application-models/access-dataability.md b/zh-cn/application-dev/application-models/access-dataability.md index 78a60c83e3..cacea2330f 100644 --- a/zh-cn/application-dev/application-models/access-dataability.md +++ b/zh-cn/application-dev/application-models/access-dataability.md @@ -32,10 +32,13 @@ 2. 构建数æ®åº“相关的RDBæ•°æ®ã€‚ ```ts - let valuesBucket = {"name": "gaolu"} + import ohos_data_ability from '@ohos.data.dataAbility' + import rdb from '@ohos.data.rdb' + + let valuesBucket: rdb.ValuesBucket = {"name": "gaolu"} let da = new ohos_data_ability.DataAbilityPredicates() - let valArray =new Array("value1"); - let cars = new Array({"batchInsert1" : "value1",}); + let valArray = new Array("value1"); + let cars = new Array({"batchInsert1" : "value1",} as rdb.ValuesBucket); ``` 注:关于DataAbilityPredicates的详细内容,请å‚考[DataAbilityè°“è¯](../reference/apis/js-apis-data-ability.md)。 @@ -43,11 +46,13 @@ 3. 调用insert方法å‘指定的DataAbilityå模å—æ’入数æ®ã€‚ ```ts + import { BusinessError } from '@ohos.base'; + // callbackæ–¹å¼è°ƒç”¨: DAHelper.insert( urivar, valuesBucket, - (error, data) => { + (error: BusinessError, data: number) => { console.info("DAHelper insert result: " + data) } ); @@ -55,10 +60,15 @@ ```ts + import featureAbility from '@ohos.ability.featureAbility' + import { BusinessError } from '@ohos.base'; + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // promiseæ–¹å¼è°ƒç”¨(await需è¦åœ¨async方法ä¸ä½¿ç”¨): let datainsert = await DAHelper.insert(urivar, valuesBucket).then((data) => { console.info("insert success."); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error("insert failed."); }); ``` @@ -66,6 +76,10 @@ 4. 调用deleteæ–¹æ³•åˆ é™¤DataAbilityå模å—ä¸æŒ‡å®šçš„æ•°æ®ã€‚ ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // callbackæ–¹å¼è°ƒç”¨: DAHelper.delete( urivar, @@ -78,6 +92,10 @@ ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // promiseæ–¹å¼è°ƒç”¨(await需è¦åœ¨async方法ä¸ä½¿ç”¨): let datadelete = await DAHelper.delete( urivar, @@ -88,6 +106,10 @@ 5. 调用update方法更新指定DataAbilityå模å—ä¸çš„æ•°æ®ã€‚ ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // callbackæ–¹å¼è°ƒç”¨: DAHelper.update( urivar, @@ -101,6 +123,10 @@ ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // promiseæ–¹å¼è°ƒç”¨(await需è¦åœ¨async方法ä¸ä½¿ç”¨): let dataupdate = await DAHelper.update( urivar, @@ -112,6 +138,10 @@ 6. 调用query方法在指定的DataAbilityå模å—ä¸æŸ¥æ‰¾æ•°æ®ã€‚ ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // callbackæ–¹å¼è°ƒç”¨: DAHelper.query( urivar, @@ -125,6 +155,10 @@ ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // promiseæ–¹å¼è°ƒç”¨(await需è¦åœ¨async方法ä¸ä½¿ç”¨): let dataquery = await DAHelper.query( urivar, @@ -136,6 +170,10 @@ 7. 调用batchInsert方法å‘指定的DataAbilityå模å—批é‡æ’入数æ®ã€‚ ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // callbackæ–¹å¼è°ƒç”¨: DAHelper.batchInsert( urivar, @@ -148,6 +186,10 @@ ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // promiseæ–¹å¼è°ƒç”¨(await需è¦åœ¨async方法ä¸ä½¿ç”¨): let databatchInsert = await DAHelper.batchInsert( urivar, @@ -158,6 +200,10 @@ 8. 调用executeBatch方法å‘指定的DataAbilityå模å—进行数æ®çš„批é‡å¤„ç†ã€‚ ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // callbackæ–¹å¼è°ƒç”¨: DAHelper.executeBatch( urivar, @@ -168,7 +214,7 @@ valuesBucket: {"executeBatch" : "value1",}, predicates: da, expectedCount:0, - predicatesBackReferences: null, + predicatesBackReferences: undefined, interrupted:true, } ], @@ -180,6 +226,10 @@ ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); // promiseæ–¹å¼è°ƒç”¨(await需è¦åœ¨async方法ä¸ä½¿ç”¨): let dataexecuteBatch = await DAHelper.executeBatch( urivar, @@ -193,7 +243,7 @@ }, predicates: da, expectedCount:0, - predicatesBackReferences: null, + predicatesBackReferences: undefined, interrupted:true, } ] diff --git a/zh-cn/application-dev/application-models/api-switch-overview.md b/zh-cn/application-dev/application-models/api-switch-overview.md index 104f5f4ba6..2500e98360 100644 --- a/zh-cn/application-dev/application-models/api-switch-overview.md +++ b/zh-cn/application-dev/application-models/api-switch-overview.md @@ -32,7 +32,7 @@ startAbility接å£ç”±FA模型切æ¢åˆ°Stage模型的示例: // context为Ability对象的æˆå‘˜ï¼Œåœ¨éžAbilityå¯¹è±¡å†…éƒ¨è°ƒç”¨éœ€è¦ // å°†Contextå¯¹è±¡ä¼ é€’è¿‡åŽ» - let wantInfo = { + let wantInfo: Want = { bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; diff --git a/zh-cn/application-dev/application-models/application-context-fa.md b/zh-cn/application-dev/application-models/application-context-fa.md index fda02355bc..10259edd5a 100644 --- a/zh-cn/application-dev/application-models/application-context-fa.md +++ b/zh-cn/application-dev/application-models/application-context-fa.md @@ -17,6 +17,8 @@ import featureAbility from "@ohos.ability.featureAbility"; ```ts +import featureAbility from "@ohos.ability.featureAbility"; + let context = featureAbility.getContext() ``` diff --git a/zh-cn/application-dev/application-models/application-context-stage.md b/zh-cn/application-dev/application-models/application-context-stage.md index 846c9c0029..10f4e1796f 100644 --- a/zh-cn/application-dev/application-models/application-context-stage.md +++ b/zh-cn/application-dev/application-models/application-context-stage.md @@ -286,7 +286,7 @@ const TAG: string = '[Example].[Entry].[EntryAbility]'; export default class EntryAbility extends UIAbility { // 定义生命周期ID - lifecycleId: number; + lifecycleId: number = -1; onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { // 定义生命周期回调对象 diff --git a/zh-cn/application-dev/application-models/bind-serviceability-from-stage.md b/zh-cn/application-dev/application-models/bind-serviceability-from-stage.md index 800e875297..0f5e318d48 100644 --- a/zh-cn/application-dev/application-models/bind-serviceability-from-stage.md +++ b/zh-cn/application-dev/application-models/bind-serviceability-from-stage.md @@ -25,7 +25,7 @@ export default class EntryAbility extends UIAbility { } onWindowStageCreate(windowStage: window.WindowStage) { console.info("EntryAbility onWindowStageCreate") - let want = { + let want: Want = { bundleName: "com.ohos.fa", abilityName: "ServiceAbility", }; diff --git a/zh-cn/application-dev/application-models/create-dataability.md b/zh-cn/application-dev/application-models/create-dataability.md index 4c12f8543c..638230ba26 100644 --- a/zh-cn/application-dev/application-models/create-dataability.md +++ b/zh-cn/application-dev/application-models/create-dataability.md @@ -7,56 +7,71 @@ 创建DataAbility的代ç 示例如下: ```ts -import featureAbility from '@ohos.ability.featureAbility' -import dataAbility from '@ohos.data.dataAbility' -import relationalStore from '@ohos.data.relationalStore' +import featureAbility from '@ohos.ability.featureAbility'; +import dataAbility from '@ohos.data.dataAbility'; +import relationalStore from '@ohos.data.relationalStore'; +import Want from '@ohos.app.ability.Want'; +import { AsyncCallback, BusinessError } from '@ohos.base'; +import rdb from '@ohos.data.rdb'; const TABLE_NAME = 'book' const STORE_CONFIG: relationalStore.StoreConfig = { name: 'book.db',securityLevel: 1 } const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)' -let rdbStore: relationalStore.RdbStore = undefined +let rdbStore: relationalStore.RdbStore | undefined = undefined -export default { - onInitialized(abilityInfo) { - console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName) +export default class DataAbility { + onInitialized(want: Want) { + console.info('DataAbility onInitialized, abilityInfo:' + want.bundleName) let context = featureAbility.getContext() relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => { console.info('DataAbility getRdbStore callback') store.executeSql(SQL_CREATE_TABLE, []) rdbStore = store }); - }, - insert(uri, valueBucket, callback) { + }; + insert(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback<number>) { console.info('DataAbility insert start') - rdbStore.insert(TABLE_NAME, valueBucket, callback) - }, - batchInsert(uri, valueBuckets, callback) { + if (rdbStore) { + rdbStore.insert(TABLE_NAME, valueBucket, callback) + } + }; + batchInsert(uri: string, valueBuckets: Array<rdb.ValuesBucket>, callback: AsyncCallback<number>) { console.info('DataAbility batch insert start') - for (let i = 0;i < valueBuckets.length; i++) { - console.info('DataAbility batch insert i=' + i) - if (i < valueBuckets.length - 1) { - rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: any, num: number) => { - console.info('DataAbility batch insert ret=' + num) - }) - } else { - rdbStore.insert(TABLE_NAME, valueBuckets[i], callback) + if (rdbStore) { + for (let i = 0;i < valueBuckets.length; i++) { + console.info('DataAbility batch insert i=' + i) + if (i < valueBuckets.length - 1) { + rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: BusinessError, num: number) => { + console.info('DataAbility batch insert ret=' + num) + }) + } else { + rdbStore.insert(TABLE_NAME, valueBuckets[i], callback) + } } } - }, - query(uri, columns, predicates, callback) { + }; + query(uri: string, columns: Array<string>, predicates: dataAbility.DataAbilityPredicates, + callback: AsyncCallback<relationalStore.ResultSet>) { console.info('DataAbility query start') let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) - rdbStore.query(rdbPredicates, columns, callback) - }, - update(uri, valueBucket, predicates, callback) { + if (rdbStore) { + rdbStore.query(rdbPredicates, columns, callback) + } + }; + update(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, + callback: AsyncCallback<number>) { console.info('DataAbilityupdate start') let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) - rdbStore.update(valueBucket, rdbPredicates, callback) - }, - delete(uri, predicates, callback) { + if (rdbStore) { + rdbStore.update(valueBucket, rdbPredicates, callback) + } + }; + delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>) { console.info('DataAbilitydelete start') let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) - rdbStore.delete(rdbPredicates, callback) - } + if (rdbStore) { + rdbStore.delete(rdbPredicates, callback) + } + }; }; ``` diff --git a/zh-cn/application-dev/application-models/create-pageability.md b/zh-cn/application-dev/application-models/create-pageability.md index c653379c1c..c736fc890e 100644 --- a/zh-cn/application-dev/application-models/create-pageability.md +++ b/zh-cn/application-dev/application-models/create-pageability.md @@ -4,28 +4,28 @@ å¼€å‘者需è¦é‡å†™app.js/app.etsä¸çš„生命周期回调函数,开å‘者通过DevEco Studioå¼€å‘å¹³å°åˆ›å»ºPageAbility时,DevEco Studio会在app.js/app.etsä¸é»˜è®¤ç”ŸæˆonCreate()å’ŒonDestroy()方法,其他方法需è¦å¼€å‘者自行实现。接å£è¯´æ˜Žå‚è§å‰è¿°ç« 节,创建PageAbility示例如下: ```ts -export default { +export default class EntryAbility { onCreate() { console.info('Application onCreate') - }, + }; onDestroy() { console.info('Application onDestroy') - }, + }; onShow() { console.info('Application onShow') - }, + }; onHide() { console.info('Application onHide') - }, + }; onActive() { console.info('Application onActive') - }, + }; onInactive() { console.info('Application onInactive') - }, + }; onNewWant() { console.info('Application onNewWant') - }, + }; } ``` @@ -84,14 +84,13 @@ import fs from '@ohos.file.fs'; try { console.info('Begin to getOrCreateDistributedDir'); dir = await featureAbility.getContext().getOrCreateDistributedDir(); - console.info('distribute dir is ' + dir) + console.info('distribute dir is ' + dir); + let fd: number; + let path = dir + "/a.txt"; + fd = fs.openSync(path, fs.OpenMode.READ_WRITE).fd; + fs.close(fd); } catch (error) { console.error('getOrCreateDistributedDir failed with ' + error); } - - let fd: number; - let path = dir + "/a.txt"; - fd = fs.openSync(path, fs.OpenMode.READ_WRITE).fd; - fs.close(fd); })() ``` diff --git a/zh-cn/application-dev/application-models/create-serviceability.md b/zh-cn/application-dev/application-models/create-serviceability.md index e634d79ff1..3d4f584d20 100644 --- a/zh-cn/application-dev/application-models/create-serviceability.md +++ b/zh-cn/application-dev/application-models/create-serviceability.md @@ -10,29 +10,25 @@ import rpc from "@ohos.rpc" class FirstServiceAbilityStub extends rpc.RemoteObject { - constructor(des: any) { - if (typeof des === 'string') { - super(des) - } else { - return - } + constructor(des: string) { + super(des); } } - export default { + export default class ServiceAbility { onStart() { console.info('ServiceAbility onStart') - }, + }; onStop() { console.info('ServiceAbility onStop') - }, + }; onCommand(want: Want, startId: number) { console.info('ServiceAbility onCommand') - }, + }; onConnect(want: Want) { console.info('ServiceAbility onConnect' + want) return new FirstServiceAbilityStub('test') - }, + }; onDisconnect(want: Want) { console.info('ServiceAbility onDisconnect' + want) } diff --git a/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md b/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md index 48c22c1057..54f0cec8d3 100644 --- a/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md +++ b/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md @@ -286,9 +286,6 @@ - è¿›è¡Œè·¨è®¾å¤‡è°ƒç”¨ï¼ŒèŽ·å¾—ç›®æ ‡ç«¯æœåŠ¡è¿”回的结果。 ```ts - import common from '@ohos.app.ability.common'; - import Want from '@ohos.app.ability.Want'; - import { BusinessError } from '@ohos.base'; import rpc from '@ohos.rpc'; import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; diff --git a/zh-cn/application-dev/application-models/inputmethodextentionability.md b/zh-cn/application-dev/application-models/inputmethodextentionability.md index 80c5d6145b..d529bb53cc 100644 --- a/zh-cn/application-dev/application-models/inputmethodextentionability.md +++ b/zh-cn/application-dev/application-models/inputmethodextentionability.md @@ -156,7 +156,7 @@ this.textInputClient = textInputClient; // æ¤ä¸ºè¾“入法客户端实例,由æ¤è°ƒç”¨è¾“入法框架æä¾›ç»™è¾“å…¥æ³•åº”ç”¨çš„åŠŸèƒ½æŽ¥å£ this.boardController = kbController; }) - globalThis.inputAbility.on('inputStop', () => { + inputMethodAbility.on('inputStop', () => { this.onDestroy(); // 销æ¯KeyboardController }); } @@ -286,14 +286,14 @@ // æ•°å—键盘 @Component struct numberMenu { - private numberList: sourceListType[] + private numberList: sourceListType[] = numberSourceListData; build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceEvenly }) { Flex({ justifyContent: FlexAlign.SpaceBetween }) { ForEach(this.numberList, (item: sourceListType) => { // æ•°å—键盘第一行 keyItem({ keyValue: item }) - }, (item: sourceListType) => item.content); + }, (item: sourceListType): sourceListType => item.content); } .padding({ top: "2%" }) .width("96%") diff --git a/zh-cn/application-dev/application-models/itc-with-worker.md b/zh-cn/application-dev/application-models/itc-with-worker.md index 78a4152f85..d3e45a50aa 100644 --- a/zh-cn/application-dev/application-models/itc-with-worker.md +++ b/zh-cn/application-dev/application-models/itc-with-worker.md @@ -46,7 +46,7 @@ Workerçš„å¼€å‘æ¥éª¤å¦‚下: wk.postMessage("message from main thread.") // 处ç†æ¥è‡ªworkerçº¿ç¨‹çš„æ¶ˆæ¯ - wk.onmessage = function(message) => { + wk.onmessage = (message) => { console.info("message from worker: " + message) // æ ¹æ®ä¸šåŠ¡æŒ‰éœ€åœæ¢worker线程 diff --git a/zh-cn/application-dev/application-models/mission-management-overview.md b/zh-cn/application-dev/application-models/mission-management-overview.md index 3ce286fe5f..ec270ea985 100644 --- a/zh-cn/application-dev/application-models/mission-management-overview.md +++ b/zh-cn/application-dev/application-models/mission-management-overview.md @@ -81,7 +81,7 @@ // 3.获å–å•ä¸ªä»»åŠ¡çš„详细信æ¯() let missionId = 11; // 11åªæ˜¯ç¤ºä¾‹ï¼Œå®žé™…是从系统ä¸èŽ·å–的任务id,下é¢ç±»ä¼¼ - let mission = missionManager.getMissionInfo("", missionId).catch((err) => { + let mission = missionManager.getMissionInfo("", missionId).catch((err: BusinessError) => { console.info('${err.code}'); }); diff --git a/zh-cn/application-dev/application-models/serviceextensionability.md b/zh-cn/application-dev/application-models/serviceextensionability.md index 0ea63cff53..52e16de2d6 100644 --- a/zh-cn/application-dev/application-models/serviceextensionability.md +++ b/zh-cn/application-dev/application-models/serviceextensionability.md @@ -135,11 +135,12 @@ export default class ServiceExtImpl extends IdlServiceExtStub { import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; import ServiceExtImpl from '../IdlServiceExt/idl_service_ext_impl'; import Want from '@ohos.app.ability.Want'; + import rpc from '@ohos.rpc'; const TAG: string = "[ServiceExtAbility]"; export default class ServiceExtAbility extends ServiceExtensionAbility { - serviceExtImpl = new ServiceExtImpl("ExtImpl"); + serviceExtImpl: ServiceExtImpl = new ServiceExtImpl("ExtImpl"); onCreate(want: Want) { console.info(TAG, `onCreate, want: ${want.abilityName}`); @@ -152,7 +153,7 @@ export default class ServiceExtImpl extends IdlServiceExtStub { onConnect(want: Want) { console.info(TAG, `onConnect, want: ${want.abilityName}`); // 返回ServiceExtImpl对象,客户端获å–åŽä¾¿å¯ä»¥ä¸ŽServiceExtensionAbility进行通信 - return this.serviceExtImpl; + return this.serviceExtImpl as rpc.RemoteObject; } onDisconnect(want: Want) { @@ -322,12 +323,12 @@ ServiceExtensionAbilityæœåŠ¡ç»„件在[onConnect()](../reference/apis/js-apis-ap console.info(`onConnect remote is null`); return; } - let serviceExtProxy = new IdlServiceExtProxy(remote); + let serviceExtProxy: IdlServiceExtProxy = new IdlServiceExtProxy(remote); // 通过接å£è°ƒç”¨çš„æ–¹å¼è¿›è¡Œé€šä¿¡ï¼Œå±è”½äº†RPC通信的细节,简æ´æ˜Žäº† - serviceExtProxy.processData(1, (errorCode, retVal) => { + serviceExtProxy.processData(1, (errorCode: number, retVal: number) => { console.info(`processData, errorCode: ${errorCode}, retVal: ${retVal}`); }); - serviceExtProxy.insertDataToMap('theKey', 1, (errorCode) => { + serviceExtProxy.insertDataToMap('theKey', 1, (errorCode: number) => { console.info(`insertDataToMap, errorCode: ${errorCode}`); }) }, diff --git a/zh-cn/application-dev/application-models/start-page.md b/zh-cn/application-dev/application-models/start-page.md index d3555be037..ca1ce7a7ec 100644 --- a/zh-cn/application-dev/application-models/start-page.md +++ b/zh-cn/application-dev/application-models/start-page.md @@ -31,10 +31,31 @@ async function restartAbility() { ```ts import Want from '@ohos.app.ability.Want'; -export default { - onNewWant(want: Want) { - globalThis.newWant = want +export class GlobalContext { + private constructor() {} + private static instance: GlobalContext; + private _objects = new Map<string, Object>(); + + public static getContext(): GlobalContext { + if (!GlobalContext.instance) { + GlobalContext.instance = new GlobalContext(); } + return GlobalContext.instance; + } + + getObject(value: string): Object | undefined { + return this._objects.get(value); + } + + setObject(key: string, objectClass: Object): void { + this._objects.set(key, objectClass); + } +} + +export default class EntryAbility{ + onNewWant(want: Want) { + GlobalContext.getContext().setObject("newWant", want); + } } ``` @@ -42,7 +63,9 @@ export default { åœ¨ç›®æ ‡ç«¯é¡µé¢çš„自定义组件ä¸èŽ·å–包å«é¡µé¢ä¿¡æ¯çš„wantå‚æ•°å¹¶æ ¹æ®uriåšè·¯ç”±å¤„ç†ï¼š ```ts -import router from '@ohos.router' +import router from '@ohos.router'; +import { GlobalContext } from '../GlobalContext' + @Entry @Component struct Index { @@ -50,10 +73,10 @@ struct Index { onPageShow() { console.info('Index onPageShow') - let newWant: Want = globalThis.newWant + let newWant: Want = GlobalContext.getContext().getObject("newWant") if (newWant.hasOwnProperty("page")) { router.push({ url: newWant.page }); - globalThis.newWant = undefined + GlobalContext.getContext().setObject("newWant", undefined) } } @@ -78,7 +101,9 @@ struct Index { 调用方的页é¢ä¸å®žçŽ°æŒ‰é’®ç‚¹å‡»è§¦å‘startAbility方法å¯åŠ¨ç›®æ ‡ç«¯PageAbility,startAbility方法的入å‚wantä¸æºå¸¦æŒ‡å®šé¡µé¢ä¿¡æ¯ï¼Œç¤ºä¾‹ä»£ç 如下: ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base'; + @Entry @Component struct Index { @@ -96,7 +121,7 @@ struct Index { } }).then((data) => { console.info("startAbility finish"); - }).catch((err) => { + }).catch((err: BusinessError) => { console.info("startAbility failed errcode:" + err.code) }) }) @@ -111,7 +136,7 @@ struct Index { } }).then((data) => { console.info("startAbility finish"); - }).catch((err) => { + }).catch((err: BusinessError) => { console.info("startAbility failed errcode:" + err.code) }) }) @@ -129,18 +154,20 @@ struct Index { import featureAbility from '@ohos.ability.featureAbility'; import router from '@ohos.router'; -export default { +export default class EntryAbility { onCreate() { featureAbility.getWant().then((want) => { - if (want.parameters.page) { - router.push({ - url: want.parameters.page - }) + if (want.parameters) { + if (want.parameters.page) { + router.push({ + url: want.parameters.page + }) + } } }) - }, + }; onDestroy() { // ... - }, + }; } ``` diff --git a/zh-cn/application-dev/application-models/uiability-data-sync-with-ui.md b/zh-cn/application-dev/application-models/uiability-data-sync-with-ui.md index 6b26e81772..f9b3ef6492 100644 --- a/zh-cn/application-dev/application-models/uiability-data-sync-with-ui.md +++ b/zh-cn/application-dev/application-models/uiability-data-sync-with-ui.md @@ -70,7 +70,7 @@ 3. 在UIAbility的注册事件回调ä¸å¯ä»¥å¾—到对应的触å‘事件结果,è¿è¡Œæ—¥å¿—结果如下所示。 - ```ts + ```json [] [1] diff --git a/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md b/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md index 591b755f56..a9eb65d2f1 100644 --- a/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md +++ b/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md @@ -164,7 +164,12 @@ UIAbility是系统调度的最å°å•å…ƒã€‚在设备内的功能模å—之间跳 let context: common.UIAbilityContext = ...; // UIAbilityContext const RESULT_CODE: number = 1001; - // ... + let want: Want = { + deviceId: '', // deviceId为空表示本设备 + bundleName: 'com.example.myapplication', + moduleName: 'func', // moduleNameéžå¿…选 + abilityName: 'FuncAbility', + } // context为调用方UIAbilityçš„UIAbilityContext context.startAbilityForResult(want).then((data) => { @@ -561,6 +566,10 @@ export default class FuncAbility extends UIAbility { 2. 在çŸä¿¡åº”用UIAbilityçš„`onNewWant()`回调ä¸è§£æžè°ƒç”¨æ–¹ä¼ 递过æ¥çš„wantå‚数,通过调用UIContextä¸çš„[`getRouter()`](../reference/apis/js-apis-arkui-UIContext.md#getrouter)方法获å–[`Router`](../reference/apis/js-apis-arkui-UIContext.md#router)对象,并进行指定页é¢çš„跳转。æ¤æ—¶å†æ¬¡å¯åŠ¨è¯¥çŸä¿¡åº”用的UIAbility实例时,å³å¯è·³è½¬åˆ°è¯¥çŸä¿¡åº”用的UIAbility实例的指定页é¢ã€‚ ```ts + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + import UIAbility from '@ohos.app.ability.UIAbility'; + import Want from '@ohos.app.ability.Want'; + import { Router, UIContext } from '@ohos.arkui.UIContext'; import { BusinessError } from '@ohos.base'; export default class EntryAbility extends UIAbility { @@ -570,12 +579,14 @@ export default class FuncAbility extends UIAbility { onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) { if (want?.parameters?.router && want.parameters.router === 'funcA') { let funcAUrl = 'pages/Second'; - let router: Router = this.uiContext.getRouter(); - router.pushUrl({ - url: funcAUrl - }).catch((err: BusinessError) => { - console.error(`Failed to push url. Code is ${err.code}, message is ${err.message}`); - }) + if (this.uiContext) { + let router: Router = this.uiContext.getRouter(); + router.pushUrl({ + url: funcAUrl + }).catch((err: BusinessError) => { + console.error(`Failed to push url. Code is ${err.code}, message is ${err.message}`); + }) + } } } @@ -673,6 +684,8 @@ Call功能主è¦æŽ¥å£å¦‚下表所示。具体的API详è§[接å£æ–‡æ¡£](../refe ```ts + import rpc from '@ohos.rpc'; + export default class MyParcelable { num: number = 0; str: string = ''; @@ -681,14 +694,14 @@ Call功能主è¦æŽ¥å£å¦‚下表所示。具体的API详è§[接å£æ–‡æ¡£](../refe this.num = num; this.str = string; } - - marshalling(messageSequence) { + + marshalling(messageSequence: rpc.MessageSequence) { messageSequence.writeInt(this.num); messageSequence.writeString(this.str); return true; } - - unmarshalling(messageSequence) { + + unmarshalling(messageSequence: rpc.MessageSequence) { this.num = messageSequence.readInt(); this.str = messageSequence.readString(); return true; @@ -702,7 +715,12 @@ Call功能主è¦æŽ¥å£å¦‚下表所示。具体的API详è§[接å£æ–‡æ¡£](../refe ```ts + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + import UIAbility from '@ohos.app.ability.UIAbility'; + import Want from '@ohos.app.ability.Want'; import rpc from '@ohos.rpc'; + import { BusinessError } from '@ohos.base'; + import MyParcelable from './MyParcelable'; const TAG: string = '[CalleeAbility]'; const MSG_SEND_METHOD: string = 'CallSendMsg'; @@ -711,13 +729,14 @@ Call功能主è¦æŽ¥å£å¦‚下表所示。具体的API详è§[接å£æ–‡æ¡£](../refe console.info('CalleeSortFunc called'); // 获å–Callerå‘é€çš„åºåˆ—åŒ–æ•°æ® - let receivedData = new MyParcelable(0, ''); + let receivedData: MyParcelable = new MyParcelable(0, ''); data.readParcelable(receivedData); console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); - + let num: number = receivedData.num; + // ä½œç›¸åº”å¤„ç† // 返回åºåˆ—化数æ®resultç»™Caller - return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); + return new MyParcelable(num + 1, `send ${receivedData.str} succeed`) as rpc.Parcelable; } export default class CalleeAbility extends UIAbility { @@ -725,7 +744,9 @@ Call功能主è¦æŽ¥å£å¦‚下表所示。具体的API详è§[接å£æ–‡æ¡£](../refe try { this.callee.on(MSG_SEND_METHOD, sendMsgCallback); } catch (err) { - console.error(`Failed to register. Code is ${err.code}, message is ${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to register. Code is ${code}, message is ${message}`); } } @@ -733,7 +754,9 @@ Call功能主è¦æŽ¥å£å¦‚下表所示。具体的API详è§[接å£æ–‡æ¡£](../refe try { this.callee.off(MSG_SEND_METHOD); } catch (err) { - console.error(`Failed to unregister. Code is ${err.code}, message is ${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to unregister. Code is ${code}, message is ${message}`); } } } @@ -755,6 +778,7 @@ Call功能主è¦æŽ¥å£å¦‚下表所示。具体的API详è§[接å£æ–‡æ¡£](../refe ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import { Caller } from '@ohos.app.ability.UIAbility'; + import { BusinessError } from '@ohos.base'; export default class CallerAbility extends UIAbility { caller: Caller | undefined = undefined; @@ -767,13 +791,15 @@ Call功能主è¦æŽ¥å£å¦‚下表所示。具体的API详è§[接å£æ–‡æ¡£](../refe }) console.info('Succeeded in registering on release.'); } catch (err) { - console.error(`Failed to caller register on release. Code is ${err.code}, message is ${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to caller register on release. Code is ${code}, message is ${message}`); } } async onButtonGetCaller() { try { - this.caller = await context.startAbilityByCall({ + this.caller = await this.context.startAbilityByCall({ bundleName: 'com.samples.CallApplication', abilityName: 'CalleeAbility' }); @@ -784,7 +810,9 @@ Call功能主è¦æŽ¥å£å¦‚下表所示。具体的API详è§[接å£æ–‡æ¡£](../refe console.info('get caller success') this.regOnRelease(this.caller) } catch (err) { - console.error(`Failed to get caller. Code is ${err.code}, message is ${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to get caller. Code is ${code}, message is ${message}`); } } } diff --git a/zh-cn/application-dev/application-models/uiability-launch-type.md b/zh-cn/application-dev/application-models/uiability-launch-type.md index 50fb118516..02e7b462de 100644 --- a/zh-cn/application-dev/application-models/uiability-launch-type.md +++ b/zh-cn/application-dev/application-models/uiability-launch-type.md @@ -135,7 +135,9 @@ specifiedå¯åŠ¨æ¨¡å¼ä¸ºæŒ‡å®šå®žä¾‹æ¨¡å¼ï¼Œé’ˆå¯¹ä¸€äº›ç‰¹æ®Šåœºæ™¯ä½¿ç”¨ï¼ˆ // 当å‰ç¤ºä¾‹æŒ‡çš„是module1 Moduleçš„SpecifiedAbility if (want.abilityName === 'SpecifiedAbility') { // 返回的å—符串Keyæ ‡è¯†ä¸ºè‡ªå®šä¹‰æ‹¼æŽ¥çš„å—符串内容 - return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; + if (want.parameters) { + return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; + } } return ''; diff --git a/zh-cn/application-dev/application-models/uiability-lifecycle.md b/zh-cn/application-dev/application-models/uiability-lifecycle.md index 6165f1c529..1df4b383b8 100644 --- a/zh-cn/application-dev/application-models/uiability-lifecycle.md +++ b/zh-cn/application-dev/application-models/uiability-lifecycle.md @@ -95,9 +95,10 @@ export default class EntryAbility extends UIAbility { ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; +import { BusinessError } from '@ohos.base'; export default class EntryAbility extends UIAbility { - windowStage: window.WindowStage; + windowStage: window.WindowStage | undefined = undefined; // ... onWindowStageCreate(windowStage: window.WindowStage) { @@ -109,9 +110,13 @@ export default class EntryAbility extends UIAbility { // 释放UIèµ„æº // 例如在onWindowStageDestroy()ä¸æ³¨é”€èŽ·ç„¦/失焦ç‰WindowStage事件 try { - this.windowStage.off('windowStageEvent'); + if (this.windowStage) { + this.windowStage.off('windowStageEvent'); + } } catch (err) { - console.error(`Failed to disable the listener for window stage event changes. Code is ${err.code}, message is ${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to disable the listener for windowStageEvent. Code is ${code}, message is ${message}`); }; } } -- GitLab