提交 ce7f94d6 编写于 作者: L liuliu

update

Signed-off-by: Nliuliu <liuliu40@huawei.com>
Change-Id: I29c06ef43142bb46f1f828c1135d74b0528bd7a6
上级 f209daf2
......@@ -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;
}
```
......
......@@ -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,
}
]
......
......@@ -32,7 +32,7 @@ startAbility接口由FA模型切换到Stage模型的示例:
// context为Ability对象的成员,在非Ability对象内部调用需要
// 将Context对象传递过去
let wantInfo = {
let wantInfo: Want = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
......
......@@ -17,6 +17,8 @@ import featureAbility from "@ohos.ability.featureAbility";
```ts
import featureAbility from "@ohos.ability.featureAbility";
let context = featureAbility.getContext()
```
......
......@@ -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) {
// 定义生命周期回调对象
......
......@@ -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",
};
......
......@@ -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)
}
};
};
```
......@@ -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);
})()
```
......@@ -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)
}
......
......@@ -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';
......
......@@ -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%")
......
......@@ -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线程
......
......@@ -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}');
});
......
......@@ -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}`);
})
},
......
......@@ -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() {
// ...
},
};
}
```
......@@ -70,7 +70,7 @@
3. 在UIAbility的注册事件回调中可以得到对应的触发事件结果,运行日志结果如下所示。
```ts
```json
[]
[1]
......
......@@ -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}`);
}
}
}
......
......@@ -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 '';
......
......@@ -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}`);
};
}
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册