提交 fd693aca 编写于 作者: L liuliu

doc arkts

Signed-off-by: Nliuliu <liuliu40@huawei.com>
Change-Id: I8a6ed554263621d2feb16d2577b3c243bba06901
上级 a137aadf
......@@ -217,51 +217,44 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl
async onRemoteMessageRequest(code: number, data, reply, option): Promise<boolean> {
console.log("onRemoteMessageRequest called, code = " + code);
switch(code) {
case IdlTestServiceStub.COMMAND_TEST_INT_TRANSACTION: {
let _data = data.readInt();
this.testIntTransaction(_data, (errCode, returnValue) => {
reply.writeInt(errCode);
if (errCode == 0) {
reply.writeInt(returnValue);
}
});
return true;
}
case IdlTestServiceStub.COMMAND_TEST_STRING_TRANSACTION: {
let _data = data.readString();
this.testStringTransaction(_data, (errCode) => {
reply.writeInt(errCode);
});
return true;
}
case IdlTestServiceStub.COMMAND_TEST_MAP_TRANSACTION: {
let _data = new Map();
let _dataSize = data.readInt();
for (let i = 0; i < _dataSize; ++i) {
let key = data.readInt();
let value = data.readInt();
_data.set(key, value);
if (code == IdlTestServiceStub.COMMAND_TEST_INT_TRANSACTION) {
let _data = data.readInt();
this.testIntTransaction(_data, (errCode, returnValue) => {
reply.writeInt(errCode);
if (errCode == 0) {
reply.writeInt(returnValue);
}
this.testMapTransaction(_data, (errCode) => {
reply.writeInt(errCode);
});
return true;
}
case IdlTestServiceStub.COMMAND_TEST_ARRAY_TRANSACTION: {
let _data = data.readStringArray();
this.testArrayTransaction(_data, (errCode, returnValue) => {
reply.writeInt(errCode);
if (errCode == 0) {
reply.writeInt(returnValue);
}
});
return true;
}
default: {
console.log("invalid request code" + code);
break;
});
return true;
} else if (code == IdlTestServiceStub.COMMAND_TEST_STRING_TRANSACTION) {
let _data = data.readString();
this.testStringTransaction(_data, (errCode) => {
reply.writeInt(errCode);
});
return true;
} else if (code == IdlTestServiceStub.COMMAND_TEST_MAP_TRANSACTION) {
let _data: Map<number, number> = new Map();
let _dataSize = data.readInt();
for (let i = 0; i < _dataSize; ++i) {
let key = data.readInt();
let value = data.readInt();
_data.set(key, value);
}
this.testMapTransaction(_data, (errCode) => {
reply.writeInt(errCode);
});
return true;
} else if (code == IdlTestServiceStub.COMMAND_TEST_ARRAY_TRANSACTION) {
let _data = data.readStringArray();
this.testArrayTransaction(_data, (errCode, returnValue) => {
reply.writeInt(errCode);
if (errCode == 0) {
reply.writeInt(returnValue);
}
});
return true;
} else {
console.log("invalid request code" + code);
}
return false;
}
......@@ -372,7 +365,7 @@ function callbackTestArrayTransaction(result: number, ret: number): void {
}
}
var onAbilityConnectDone = {
let onAbilityConnectDone = {
onConnect:function (elementName, proxy) {
let testProxy = new IdlTestServiceProxy(proxy);
let testMap = new Map();
......
......@@ -47,23 +47,23 @@
```ts
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
function implicitStartAbility() {
let context = getContext(this) as common.UIAbilityContext;
let wantInfo = {
// uncomment line below if wish to implicitly query only in the specific bundle.
// bundleName: 'com.example.myapplication',
'action': 'ohos.want.action.viewData',
// entities can be omitted.
'entities': ['entity.system.browsable'],
'uri': 'https://www.test.com:8080/query/student'
}
context.startAbility(wantInfo).then(() => {
...
}).catch((err) => {
...
})
let context = getContext(this) as common.UIAbilityContext;
let wantInfo: Want = {
// uncomment line below if wish to implicitly query only in the specific bundle.
// bundleName: 'com.example.myapplication',
'action': 'ohos.want.action.viewData',
// entities can be omitted.
'entities': ['entity.system.browsable'],
'uri': 'https://www.test.com:8080/query/student'
}
context.startAbility(wantInfo).then(() => {
// ...
}).catch((err: BusinessError) => {
// ...
})
```
匹配过程分析:
......
......@@ -18,12 +18,13 @@ DevEco Studio默认工程中未自动生成AbilityStage,如需要使用Ability
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
import Want from '@ohos.app.ability.Want';
export default class MyAbilityStage extends AbilityStage {
onCreate() {
// 应用的HAP在首次加载的时,为该Module初始化操作
}
onAcceptWant(want) {
onAcceptWant(want: Want) {
// 仅specified模式下触发
return "MyAbilityStage";
}
......@@ -58,9 +59,10 @@ DevEco Studio默认工程中未自动生成AbilityStage,如需要使用Ability
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
export default class MyAbilityStage extends AbilityStage {
onMemoryLevel(level) {
onMemoryLevel(level: AbilityConstant.MemoryLevel) {
// 根据系统可用内存的变化情况,释放不必要的内存
}
}
......
......@@ -11,15 +11,16 @@ startAbility接口由FA模型切换到Stage模型的示例:
```ts
import fa from '@ohos.ability.featureAbility';
let parameter = {
import { BusinessError } from '@ohos.base';
fa.startAbility({
"want": {
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.EntryAbility"
}
}
fa.startAbility(parameter).then((data) => {
}).then((data) => {
console.info('startAbility success');
}).catch((error) => {
}).catch((error: BusinessError) => {
console.error('startAbility failed.');
})
```
......@@ -27,15 +28,17 @@ startAbility接口由FA模型切换到Stage模型的示例:
- Stage示例示例
```ts
import Want from '@ohos.app.ability.Want';
// context为Ability对象的成员,在非Ability对象内部调用需要
// 将Context对象传递过去
let wantInfo = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
this.context.startAbility(wantInfo).then((data) => {
this.context.startAbility(wantInfo).then(() => {
console.info('startAbility success.');
}).catch((error) => {
}).catch((error: BusinessError) => {
console.error('startAbility failed.');
})
```
......@@ -28,39 +28,35 @@ let context = featureAbility.getContext()
1. 查询Bundle信息。
```ts
import featureAbility from '@ohos.ability.featureAbility'
export default {
onCreate() {
// 获取context并调用相关方法
let context = featureAbility.getContext();
context.getBundleName((data, bundleName)=>{
console.info("ability bundleName:" + bundleName)
});
console.info('Application onCreate')
},
onDestroy() {
console.info('Application onDestroy')
},
}
import featureAbility from '@ohos.ability.featureAbility'
export function onCreate() {
// 获取context并调用相关方法
let context = featureAbility.getContext();
context.getBundleName((data, bundleName)=>{
console.info("ability bundleName:" + bundleName)
});
console.info('Application onCreate')
}
export function onDestroy() {
console.info('Application onDestroy')
}
```
2. 设置当前featureAbility的显示方向。
```ts
import featureAbility from '@ohos.ability.featureAbility'
import bundleManager from '@ohos.bundle.bundleManager';
export default {
onCreate() {
// 获取context并调用相关方法
let context = featureAbility.getContext();
context.setDisplayOrientation(bundleManager.DisplayOrientation.LANDSCAPE).then(() => {
console.info("Set display orientation.")
})
console.info('Application onCreate')
},
onDestroy() {
console.info('Application onDestroy')
},
}
import featureAbility from '@ohos.ability.featureAbility'
import bundleManager from '@ohos.bundle.bundleManager';
export function onCreate() {
// 获取context并调用相关方法
let context = featureAbility.getContext();
context.setDisplayOrientation(bundleManager.DisplayOrientation.LANDSCAPE).then(() => {
console.info("Set display orientation.")
})
console.info('Application onCreate')
}
export function onDestroy() {
console.info('Application onDestroy')
}
```
......@@ -16,8 +16,10 @@
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
let uiAbilityContext = this.context;
...
}
......@@ -31,8 +33,9 @@
```ts
import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
import Want from '@ohos.app.ability.Want';
export default class MyService extends ServiceExtensionAbility {
onCreate(want) {
onCreate(want: Want) {
let serviceExtensionContext = this.context;
...
}
......@@ -53,8 +56,10 @@
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
let applicationContext = this.context.getApplicationContext();
...
}
......@@ -96,9 +101,11 @@
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
let applicationContext = this.context.getApplicationContext();
let cacheDir = applicationContext.cacheDir;
let tempDir = applicationContext.tempDir;
......@@ -131,9 +138,11 @@
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
let cacheDir = this.context.cacheDir;
let tempDir = this.context.tempDir;
let filesDir = this.context.filesDir;
......@@ -167,9 +176,11 @@
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import contextConstant from '@ohos.app.ability.contextConstant';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// 存储普通信息前,切换到EL1设备级加密
if (this.context.area === contextConstant.AreaMode.EL2) { // 获取area
this.context.area = contextConstant.AreaMode.EL1; // 修改area
......@@ -203,9 +214,11 @@ export default class EntryAbility extends UIAbility {
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
let bundleName2 = 'com.example.application';
let context2 = this.context.createBundleContext(bundleName2);
let label2 = context2.applicationInfo.label;
......@@ -225,9 +238,11 @@ export default class EntryAbility extends UIAbility {
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
let bundleName2 = 'com.example.application';
let moduleName2 = 'module1';
let context2 = this.context.createModuleContext(bundleName2, moduleName2);
......@@ -240,9 +255,11 @@ export default class EntryAbility extends UIAbility {
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
let moduleName2 = 'module1';
let context2 = this.context.createModuleContext(moduleName2);
...
......@@ -260,6 +277,9 @@ export default class EntryAbility extends UIAbility {
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
const TAG: string = '[Example].[Entry].[EntryAbility]';
......@@ -268,9 +288,9 @@ export default class EntryAbility extends UIAbility {
// 定义生命周期ID
lifecycleId: number;
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// 定义生命周期回调对象
let abilityLifecycleCallback = {
let abilityLifecycleCallback: AbilityLifecycleCallback = {
// 当UIAbility创建时被调用
onAbilityCreate(uiAbility) {
console.info(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
......
......@@ -11,29 +11,33 @@ UIAbility关联访问ServiceAbility和UIAbility关联访问ServiceExtensionAbili
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
console.info("EntryAbility onCreate");
}
onDestroy() {
console.info("EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
onWindowStageCreate(windowStage: window.WindowStage) {
console.info("EntryAbility onWindowStageCreate")
let want = {
bundleName: "com.ohos.fa",
abilityName: "ServiceAbility",
};
let options = {
onConnect:function (elementName, proxy) {
let options: common.ConnectOptions = {
onConnect: (elementName, proxy) => {
console.info("onConnect called.");
},
onDisconnect:function (elementName) {
onDisconnect: (elementName) => {
console.info("onDisconnect called.");
},
onFailed:function (code) {
onFailed: (code) => {
console.info("onFailed code is: " + code);
}
};
......@@ -58,29 +62,31 @@ export default class EntryAbility extends UIAbility {
```ts
import Extension from '@ohos.app.ability.ServiceExtensionAbility'
import Extension from '@ohos.app.ability.ServiceExtensionAbility';
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
export default class ServiceExtension extends Extension {
onCreate(want) {
onCreate(want: Want) {
console.info("ServiceExtension onCreate")
}
onDestroy() {
console.info("ServiceExtension onDestroy")
}
onRequest(want, startId) {
onRequest(want: Want, startId: number) {
console.info("ServiceExtension onRequest")
let wantFA = {
let wantFA: Want = {
bundleName: "com.ohos.fa",
abilityName: "ServiceAbility",
};
let options = {
onConnect:function (elementName, proxy) {
let options: common.ConnectOptions = {
onConnect: (elementName, proxy) => {
console.info("onConnect called.");
},
onDisconnect:function (elementName) {
onDisconnect: (elementName) => {
console.info("onDisconnect called.");
},
onFailed:function (code) {
onFailed: (code) => {
console.info("onFailed code is: " + code);
}
};
......
......@@ -11,20 +11,22 @@ PageAbility关联访问ServiceExtensionAbility和PageAbility关联访问ServiceA
```ts
import featureAbility from '@ohos.ability.featureAbility';
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
let want = {
let want: Want = {
bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.ServiceExtensionAbility"
};
let faConnect = {
onConnect:function (elementName, proxy) {
let faConnect: common.ConnectOptions = {
onConnect: (elementName, proxy) => {
console.info("Faconnection onConnect called.");
},
onDisconnect:function (elementName) {
onDisconnect: (elementName) => {
console.info("Faconnection onDisconnect called.");
},
onFailed:function (code) {
onFailed: (code) => {
console.info("Faconnection onFailed code is: " + code);
}
};
......@@ -39,20 +41,22 @@ ServiceAbility/DataAbility关联访问ServiceExtensionAbility和ServiceAbility/D
```ts
import particleAbility from '@ohos.ability.particleAbility';
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
let want = {
let want: Want = {
bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.ServiceExtensionAbility"
};
let faConnect = {
onConnect:function (elementName, proxy) {
let faConnect: common.ConnectOptions = {
onConnect: (elementName, proxy) => {
console.info("Faconnection onConnect called.");
},
onDisconnect:function (elementName) {
onDisconnect: (elementName) => {
console.info("Faconnection onDisconnect called.");
},
onFailed:function (code) {
onFailed: (code) => {
console.info("Faconnection onFailed code is: " + code);
}
};
......
......@@ -19,9 +19,11 @@ PageAbility创建连接本地ServiceAbility回调实例的代码以及连接本
import rpc from "@ohos.rpc"
import promptAction from '@ohos.promptAction'
import featureAbility from '@ohos.ability.featureAbility'
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
let option = {
onConnect: function onConnectCallback(element, proxy) {
let option: common.ConnectOptions = {
onConnect: (element, proxy) => {
console.info(`onConnectLocalService onConnectDone`)
if (proxy === null) {
promptAction.showToast({
......@@ -38,21 +40,21 @@ let option = {
message: "Connect service success"
})
},
onDisconnect: function onDisconnectCallback(element) {
onDisconnect: (element) => {
console.info(`onConnectLocalService onDisconnectDone element:${element}`)
promptAction.showToast({
message: "Disconnect service success"
})
},
onFailed: function onFailedCallback(code) {
onFailed: (code) => {
console.info(`onConnectLocalService onFailed errCode:${code}`)
promptAction.showToast({
message: "Connect local service onFailed"
})
}
}
};
let request = {
let request: Want = {
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.ServiceAbility",
}
......@@ -69,7 +71,7 @@ Service侧把自身的实例返回给调用侧的示例代码如下:
import rpc from "@ohos.rpc"
class FirstServiceAbilityStub extends rpc.RemoteObject {
constructor(des: any) {
constructor(des: Object) {
if (typeof des === 'string') {
super(des)
} else {
......@@ -77,7 +79,7 @@ class FirstServiceAbilityStub extends rpc.RemoteObject {
}
}
onRemoteRequest(code: number, data: any, reply: any, option: any) {
onRemoteRequest(code: number, data: rpc.MessageParcel, reply: rpc.MessageParcel, option: rpc.MessageOption) {
console.info(`onRemoteRequest called`)
if (code === 1) {
let string = data.readString()
......
......@@ -12,7 +12,7 @@ import dataAbility from '@ohos.data.dataAbility'
import relationalStore from '@ohos.data.relationalStore'
const TABLE_NAME = 'book'
const STORE_CONFIG = { name: 'book.db',securityLevel: 1 }
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
......
......@@ -6,6 +6,7 @@
重写ServiceAbility的生命周期方法,添加其他Ability请求与ServiceAbility交互时的处理方法。
```ts
import Want from '@ohos.app.ability.Want';
import rpc from "@ohos.rpc"
class FirstServiceAbilityStub extends rpc.RemoteObject {
......@@ -25,14 +26,14 @@
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' + want)
return new FirstServiceAbilityStub('test')
},
onDisconnect(want) {
onDisconnect(want: Want) {
console.info('ServiceAbility onDisconnect' + want)
}
}
......
......@@ -27,17 +27,18 @@
const REQUEST_CODE = 99;
class StubTest extends rpc.RemoteObject {
constructor(des) {
constructor(des: string) {
super(des);
}
// 接收应用传递过来的消息处理,以及将处理的结果返回给应用
onRemoteMessageRequest(code, data, reply, option) {
onRemoteMessageRequest(code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence,
option: rpc.MessageOption) {
if (code === REQUEST_CODE) {
// 接收应用传递过来的数据
// 应用使用多次调用data.writeInt()写入多个数据时,驱动可以通过多次调用data.readInt()方法接收对应的数据
let optFir = data.readInt();
let optSec = data.readInt();
let optFir: number = data.readInt();
let optSec: number = data.readInt();
// 驱动将数据的处理结果返回给应用
// 示例中为接收了两个数据,并将两个数据的求和返回给应用
reply.writeInt(optFir + optSec);
......@@ -52,6 +53,7 @@
```ts
import DriverExtensionAbility from '@ohos.app.ability.DriverExtensionAbility';
import Want from '@ohos.app.ability.Want';
import rpc from '@ohos.rpc';
const TAG: string = '[Example].[Entry].[DriverExtAbility]';
......@@ -62,24 +64,24 @@
}
export default class DriverExtAbility extends DriverExtensionAbility {
onInit(want) {
onInit(want: Want) {
console.info(TAG, `onInit, want: ${want.abilityName}`);
}
onRelease() {
console.info(TAG, `onRelease, want: ${want.abilityName}`);
console.info(TAG, `onRelease`);
}
onConnect(want) {
onConnect(want: Want) {
console.info(TAG, `onConnect, want: ${want.abilityName}`);
return new StubTest("test");
}
onDisconnect(want) {
onDisconnect(want: Want) {
console.info(TAG, `onDisconnect, want: ${want.abilityName}`);
}
onDump() {
onDump(params: Array<string>) {
console.info(TAG, `onDump, params:` + JSON.stringify(params));
return ['params'];
}
......
......@@ -61,7 +61,7 @@ export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbil
​ 4.在工程Module对应的[module.json5](../quick-start/module-configuration-file.md)配置文件中注册ServiceExtensionAbility,type标签需要设置为“enterpriseAdmin”,srcEntry标签表示当前ExtensionAbility组件所对应的代码路径。
```ts
```json
"extensionAbilities": [
{
"name": "ohos.samples.enterprise_admin_ext_ability",
......
......@@ -67,7 +67,7 @@
console.error("createDeviceManager err: " + JSON.stringify(err));
}
}
function getRemoteDeviceId() {
function getRemoteDeviceId(): string | undefined {
if (typeof dmClass === 'object' && dmClass !== null) {
let list = dmClass.getAvailableDeviceListSync();
if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') {
......@@ -286,6 +286,9 @@
- 进行跨设备调用,获得目标端服务返回的结果。
```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';
......
......@@ -55,12 +55,13 @@
在InputMethodService.ts文件中,增加导入InputMethodExtensionAbility的依赖包,自定义类继承InputMethodExtensionAbility并加上需要的生命周期回调。
```ts
import Want from '@ohos.app.ability.Want';
import InputMethodExtensionAbility from '@ohos.InputMethodExtensionAbility';
import keyboardController from './model/KeyboardController'
export default class InputDemoService extends InputMethodExtensionAbility {
onCreate(want) {
onCreate(want: Want) {
keyboardController.onCreate(this.context); // 初始化窗口并注册对输入法框架的事件监听
}
......@@ -141,7 +142,7 @@
this.panel = inputPanel;
if(this.panel) {
await this.panel.resize(dWidth, keyHeight);
await this.panel.mobeTo(0, nonBarPosition);
await this.panel.moveTo(0, nonBarPosition);
await this.panel.setUiContent('inputmethodextability/pages/Index');
}
});
......@@ -333,7 +334,7 @@
5. 在工程Module对应的[module.json5配置文件](../quick-start/module-configuration-file.md)中注册InputMethodExtensionAbility,type标签需要设置为“inputMethod”,srcEntry标签表示当前InputMethodExtensionAbility组件所对应的代码路径。
```ts
```json
{
"module": {
...
......
......@@ -13,12 +13,12 @@ Emitter的开发步骤如下:
import emitter from "@ohos.events.emitter";
// 定义一个eventId为1的事件
let event = {
let event: emitter.InnerEvent = {
eventId: 1
};
// 收到eventId为1的事件后执行该回调
let callback = (eventData) => {
let callback = (eventData: emitter.EventData) => {
console.info('event callback');
};
......@@ -32,18 +32,16 @@ Emitter的开发步骤如下:
import emitter from "@ohos.events.emitter";
// 定义一个eventId为1的事件,事件优先级为Low
let event = {
let event: emitter.InnerEvent = {
eventId: 1,
priority: emitter.EventPriority.LOW
};
let eventData = {
data: {
"content": "c",
"id": 1,
"isEmpty": false,
}
};
let data = new Map<string, Object>();
data.set("content", "c");
data.set("id", 1);
data.set("isEmpty", false);
let eventData: emitter.EventData = {data};
// 发送eventId为1的事件,事件内容为eventData
emitter.emit(event, eventData);
......
......@@ -9,7 +9,7 @@ Worker的开发步骤如下:
1. 在工程的[模块级build-profile.json5](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-building-configuration-0000001218440654#section6887184182020)文件的buildOption属性中添加配置信息。
```ts
```json
"buildOption": {
"sourceOption": {
"workers": [
......@@ -27,7 +27,7 @@ Worker的开发步骤如下:
let parent = worker.workerPort;
// 处理来自主线程的消息
parent.onmessage = function(message) {
parent.onmessage = (message) => {
console.info("onmessage: " + message)
// 发送消息到主线程
parent.postMessage("message from worker thread.")
......@@ -46,7 +46,7 @@ Worker的开发步骤如下:
wk.postMessage("message from main thread.")
// 处理来自worker线程的消息
wk.onmessage = function(message) {
wk.onmessage = function(message) => {
console.info("message from worker: " + message)
// 根据业务按需停止worker线程
......@@ -65,7 +65,7 @@ Worker的开发步骤如下:
wk.postMessage("message from main thread.")
// 处理来自worker线程的消息
wk.onmessage = function(message) {
wk.onmessage = (message) => {
console.info("message from worker: " + message)
// 根据业务按需停止worker线程
......
......@@ -36,34 +36,35 @@
```ts
import missionManager from '@ohos.app.ability.missionManager'
import { BusinessError } from '@ohos.base';
let listener = {
let listener: missionManager.MissionListener = {
// 任务创建
onMissionCreated: function (mission) {
onMissionCreated: (mission) => {
console.info("--------onMissionCreated-------")
},
// 任务销毁
onMissionDestroyed: function (mission) {
onMissionDestroyed: (mission) => {
console.info("--------onMissionDestroyed-------")
},
// 任务快照变化
onMissionSnapshotChanged: function (mission) {
onMissionSnapshotChanged: (mission) => {
console.info("--------onMissionSnapshotChanged-------")
},
// 任务被移动到前台
onMissionMovedToFront: function (mission) {
onMissionMovedToFront: (mission) => {
console.info("--------onMissionMovedToFront-------")
},
// 任务图标变化
onMissionIconUpdated: function (mission, icon) {
onMissionIconUpdated: (mission, icon) => {
console.info("--------onMissionIconUpdated-------")
},
// 任务名称变化
onMissionLabelUpdated: function (mission) {
onMissionLabelUpdated: (mission) => {
console.info("--------onMissionLabelUpdated-------")
},
// 任务实例被关闭
onMissionClosed: function (mission) {
onMissionClosed: (mission) => {
console.info("--------onMissionClosed-------")
}
};
......@@ -80,8 +81,8 @@
// 3.获取单个任务的详细信息()
let missionId = 11; // 11只是示例,实际是从系统中获取的任务id,下面类似
let mission = missionManager.getMissionInfo("", missionId).catch(function (err) {
console.info(err);
let mission = missionManager.getMissionInfo("", missionId).catch((err) => {
console.info('${err.code}');
});
// 4.获取任务快照
......@@ -116,8 +117,8 @@
});
// 9.删除全部任务
missionManager.clearAllMissions().catch(function (err) {
console.info(err);
missionManager.clearAllMissions().catch((err: BusinessError) => {
console.info('${err.code}');
});
// 10.解注册任务变化通知
......
......@@ -21,7 +21,9 @@
示例中的context的获取方式请参见[获取UIAbility的上下文信息](uiability-usage.md#获取uiability的上下文信息)。示例中的`pixelMap`的获取方式请参见[图片解码](../media/image-decoding.md)
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
let context: common.UIAbilityContext = ...; // UIAbilityContext
let pixelMap: PixelMap = ...; // 图片的PixelMap信息
context.setMissionIcon(pixelMap, (err) => {
......@@ -41,11 +43,14 @@ context.setMissionIcon(pixelMap, (err) => {
通过调用[`UIAbilityContext.setMissionLabel()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel)方法修改任务快照的名称。
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
let context: common.UIAbilityContext = this.context; // UIAbilityContext
context.setMissionLabel('test').then(() => {
console.info('Succeeded in seting mission label.');
}).catch((err) => {
}).catch((err: BusinessErrpr) => {
console.error(`Failed to set mission label. Code is ${err.code}, message is ${err.message}`);
});
```
......
......@@ -42,15 +42,17 @@ FA模型中PageAbility对应Stage模型中的UIAbility。切换步骤如下。
```ts
import Window from '@ohos.window'
onWindowStageCreate(windowStage: Window.WindowStage) {
// Main window is created, set main page for this ability
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
console.error("loadContent failed")
return;
}
});
}
import Window from '@ohos.window'
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: Window.WindowStage) {
// Main window is created, set main page for this ability
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
console.error("loadContent failed")
return;
}
});
}
}
```
......@@ -19,7 +19,7 @@ PageAbility作为可见Ability,可以通过startAbility启动有界面的且
如果需设置当前Ability可由任何应用访问,对应config.json文件的示例代码如下所示:
```ts
```json
{
"module": {
...
......
......@@ -134,27 +134,28 @@ export default class ServiceExtImpl extends IdlServiceExtStub {
```ts
import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
import ServiceExtImpl from '../IdlServiceExt/idl_service_ext_impl';
import Want from '@ohos.app.ability.Want';
const TAG: string = "[ServiceExtAbility]";
export default class ServiceExtAbility extends ServiceExtensionAbility {
serviceExtImpl = new ServiceExtImpl("ExtImpl");
onCreate(want) {
onCreate(want: Want) {
console.info(TAG, `onCreate, want: ${want.abilityName}`);
}
onRequest(want, startId) {
onRequest(want: Want, startId: number) {
console.info(TAG, `onRequest, want: ${want.abilityName}`);
}
onConnect(want) {
onConnect(want: Want) {
console.info(TAG, `onConnect, want: ${want.abilityName}`);
// 返回ServiceExtImpl对象,客户端获取后便可以与ServiceExtensionAbility进行通信
return this.serviceExtImpl;
}
onDisconnect(want) {
onDisconnect(want: Want) {
console.info(TAG, `onDisconnect, want: ${want.abilityName}`);
}
......@@ -194,15 +195,19 @@ export default class ServiceExtImpl extends IdlServiceExtStub {
1. 在系统应用中启动一个新的ServiceExtensionAbility。示例中的context的获取方式请参见[获取UIAbility的上下文信息](uiability-usage.md#获取uiability的上下文信息)
```ts
let context = ...; // UIAbilityContext
let want = {
"deviceId": "",
"bundleName": "com.example.myapplication",
"abilityName": "ServiceExtAbility"
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
let context: common.UIAbilityContext = ...; // UIAbilityContext
let want: Want = {
deviceId: "",
bundleName: "com.example.myapplication",
abilityName: "ServiceExtAbility"
};
context.startServiceExtensionAbility(want).then(() => {
console.info('Succeeded in starting ServiceExtensionAbility.');
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to start ServiceExtensionAbility. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -210,15 +215,19 @@ export default class ServiceExtImpl extends IdlServiceExtStub {
2. 在系统应用中停止一个已启动的ServiceExtensionAbility。
```ts
let context = ...; // UIAbilityContext
let want = {
"deviceId": "",
"bundleName": "com.example.myapplication",
"abilityName": "ServiceExtAbility"
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
let context: common.UIAbilityContext = ...; // UIAbilityContext
let want: Want = {
deviceId: "",
bundleName: "com.example.myapplication",
abilityName: "ServiceExtAbility"
};
context.stopServiceExtensionAbility(want).then(() => {
console.info('Succeeded in stopping ServiceExtensionAbility.');
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to stop ServiceExtensionAbility. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -226,10 +235,13 @@ export default class ServiceExtImpl extends IdlServiceExtStub {
3. 已启动的ServiceExtensionAbility停止自身。
```ts
let context = ...; // ServiceExtensionContext
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
let context: common.ServiceExtensionContext = ...; // ServiceExtensionContext
context.terminateSelf().then(() => {
console.info('Succeeded in terminating self.');
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to terminate self. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -250,12 +262,15 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
- 使用connectServiceExtensionAbility()建立与后台服务的连接。示例中的context的获取方式请参见[获取UIAbility的上下文信息](uiability-usage.md#获取uiability的上下文信息)
```ts
let want = {
"deviceId": "",
"bundleName": "com.example.myapplication",
"abilityName": "ServiceExtAbility"
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
let want: Want = {
deviceId: "",
bundleName: "com.example.myapplication",
abilityName: "ServiceExtAbility"
};
let options = {
let options: common.ConnectOptions = {
onConnect(elementName, remote) {
/* 此处的入参remote为ServiceExtensionAbility在onConnect生命周期回调中返回的对象,
* 开发者通过这个对象便可以与ServiceExtensionAbility进行通信,具体通信方式见下文
......@@ -274,16 +289,17 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
}
}
// 建立连接后返回的Id需要保存下来,在解绑服务时需要作为参数传入
let connectionId = this.context.connectServiceExtensionAbility(want, options);
let connectionId: number = this.context.connectServiceExtensionAbility(want, options);
```
- 使用disconnectServiceExtensionAbility()断开与后台服务的连接。
```ts
import { BusinessError } from '@ohos.base';
// connectionId为调用connectServiceExtensionAbility接口时的返回值,需开发者自行维护
this.context.disconnectServiceExtensionAbility(connectionId).then((data) => {
this.context.disconnectServiceExtensionAbility(connectionId).then(() => {
console.info('disconnectServiceExtensionAbility success');
}).catch((error) => {
}).catch((error: BusinessError) => {
console.error('disconnectServiceExtensionAbility failed');
})
```
......@@ -297,8 +313,9 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
```ts
// 客户端需要将服务端对外提供的idl_service_ext_proxy.ts导入到本地工程中
import IdlServiceExtProxy from '../IdlServiceExt/idl_service_ext_proxy';
import common from '@ohos.app.ability.common';
let options = {
let options: common.ConnectOptions = {
onConnect(elementName, remote) {
console.info('onConnect callback');
if (remote === null) {
......@@ -327,9 +344,11 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
```ts
import rpc from '@ohos.rpc';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
const REQUEST_CODE = 1;
let options = {
let options: common.ConnectOptions = {
onConnect(elementName, remote) {
console.info('onConnect callback');
if (remote === null) {
......@@ -351,7 +370,7 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
remote.sendMessageRequest(REQUEST_CODE, data, reply, option).then((ret) => {
let msg = reply.readInt();
console.info(`sendMessageRequest ret:${ret} msg:${msg}`);
}).catch((error) => {
}).catch((error: BusinessError) => {
console.info('sendMessageRequest failed');
});
},
......@@ -374,6 +393,7 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
```ts
import rpc from '@ohos.rpc';
import { BusinessError } from '@ohos.base';
import bundleManager from '@ohos.bundle.bundleManager';
import { processDataCallback } from './i_idl_service_ext';
import { insertDataToMapCallback } from './i_idl_service_ext';
......@@ -396,7 +416,7 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
return;
}
// 识别通过,执行正常业务逻辑
}).catch(err => {
}).catch((err: BusinessError) => {
console.info(TAG, 'getBundleNameByUid failed: ' + err.message);
});
}
......
......@@ -16,17 +16,17 @@ PageAbility相关的能力通过featureAbility提供,启动本地Ability通过
```ts
import featureAbility from '@ohos.ability.featureAbility'
import Want from '@ohos.app.ability.Want';
(async () => {
try {
console.info('Begin to start ability')
let param = {
want: {
bundleName: "com.example.myapplication",
moduleName: "entry",
abilityName: "com.example.myapplication.EntryAbility"
}
let want: Want = {
bundleName: "com.example.myapplication",
moduleName: "entry",
abilityName: "com.example.myapplication.EntryAbility"
}
await featureAbility.startAbility(param)
await featureAbility.startAbility({want})
console.info(`Start ability succeed`)
}
catch (error) {
......
......@@ -8,9 +8,10 @@
```ts
import featureAbility from '@ohos.ability.featureAbility';
import Want from '@ohos.app.ability.Want';
async function restartAbility() {
let wantInfo = {
let wantInfo: Want = {
bundleName: "com.sample.MyApplication",
abilityName: "EntryAbility",
parameters: {
......@@ -29,8 +30,9 @@ async function restartAbility() {
在目标端PageAbility的onNewWant回调中获取包含页面信息的want参数:
```ts
import Want from '@ohos.app.ability.Want';
export default {
onNewWant(want) {
onNewWant(want: Want) {
globalThis.newWant = want
}
}
......@@ -45,10 +47,10 @@ import router from '@ohos.router'
@Component
struct Index {
@State message: string = 'Router Page'
newWant = undefined
onPageShow() {
console.info('Index onPageShow')
let newWant = globalThis.newWant
let newWant: Want = globalThis.newWant
if (newWant.hasOwnProperty("page")) {
router.push({ url: newWant.page });
globalThis.newWant = undefined
......@@ -83,36 +85,38 @@ struct Index {
@State message: string = 'Hello World'
build() {
...
Button("startAbility")
.onClick(() => {
featureAbility.startAbility({
want: {
bundleName: "com.exm.myapplication",
abilityName: "com.exm.myapplication.EntryAbility",
parameters: { page: "pages/page1" }
}
}).then((data) => {
console.info("startAbility finish");
}).catch((err) => {
console.info("startAbility failed errcode:" + err.code)
Row() {
Button("startAbility")
.onClick(() => {
featureAbility.startAbility({
want: {
bundleName: "com.exm.myapplication",
abilityName: "com.exm.myapplication.EntryAbility",
parameters: { page: "pages/page1" }
}
}).then((data) => {
console.info("startAbility finish");
}).catch((err) => {
console.info("startAbility failed errcode:" + err.code)
})
})
})
...
Button("page2")
.onClick(() => {
featureAbility.startAbility({
want: {
bundleName: "com.exm.myapplication",
abilityName: "com.exm.myapplication.EntryAbility",
parameters: { page: "pages/page2" }
}
}).then((data) => {
console.info("startAbility finish");
}).catch((err) => {
console.info("startAbility failed errcode:" + err.code)
...
Button("page2")
.onClick(() => {
featureAbility.startAbility({
want: {
bundleName: "com.exm.myapplication",
abilityName: "com.exm.myapplication.EntryAbility",
parameters: { page: "pages/page2" }
}
}).then((data) => {
console.info("startAbility finish");
}).catch((err) => {
console.info("startAbility failed errcode:" + err.code)
})
})
})
...
}
...
}
}
......@@ -136,7 +140,7 @@ export default {
})
},
onDestroy() {
...
// ...
},
}
```
......@@ -13,26 +13,30 @@
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
import { BusinessError } from '@ohos.base';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
console.info("EntryAbility onCreate")
}
onDestroy() {
console.info("EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
onWindowStageCreate(windowStage: window.WindowStage) {
console.info("EntryAbility onWindowStageCreate")
windowStage.loadContent('pages/Index', (err, data) => {
...
// ...
});
let want = {
let want: Want = {
bundleName: "com.ohos.fa",
abilityName: "com.ohos.fa.EntryAbility",
};
this.context.startAbility(want).then(() => {
console.info('Start Ability successfully.');
}).catch((error) => {
}).catch((error: BusinessError) => {
console.error("Ability failed: " + JSON.stringify(error));
});
}
......@@ -58,26 +62,30 @@ UIAbility通过startAbilityForResult启动PageABility和UIAbility通过startAbil
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
import { BusinessError } from '@ohos.base';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
console.info("EntryAbility onCreate")
}
onDestroy() {
console.info("EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
onWindowStageCreate(windowStage: window.WindowStage) {
console.info("EntryAbility onWindowStageCreate")
windowStage.loadContent('pages/Index', (err, data) => {
...
// ...
});
let want = {
let want: Want = {
bundleName: "com.ohos.fa",
abilityName: "EntryAbility",
};
this.context.startAbilityForResult(want).then((result) => {
console.info('Ability verify result: ' + JSON.stringify(result));
}).catch((error) => {
}).catch((error: BusinessError) => {
console.error("Ability failed: " + JSON.stringify(error));
});
}
......@@ -101,23 +109,25 @@ export default class EntryAbility extends UIAbility {
```ts
import Extension from '@ohos.app.ability.ServiceExtensionAbility'
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
export default class ServiceExtension extends Extension {
onCreate(want) {
onCreate(want: Want) {
console.info("ServiceExtension onCreate")
}
onDestroy() {
console.info("ServiceExtension onDestroy")
}
onRequest(want, startId) {
onRequest(want: Want, startId: number) {
console.info("ServiceExtension onRequest")
let wantFA = {
let wantFA: Want = {
bundleName: "com.ohos.fa",
abilityName: "EntryAbility",
};
this.context.startAbility(wantFA).then(() => {
console.info('Start Ability successfully.');
}).catch((error) => {
}).catch((error: BusinessError) => {
console.error("Ability failed: " + JSON.stringify(error));
});
}
......
......@@ -52,7 +52,7 @@ async function RequestPermission() {
console.info('RequestPermission begin');
let array: Array<string> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
let bundleFlag = 0;
let tokenID = undefined;
let tokenID: number | undefined = undefined;
let userID = 100;
let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID);
tokenID = appInfo.accessTokenId;
......@@ -89,7 +89,7 @@ async function RequestPermission() {
```ts
import deviceManager from '@ohos.distributedHardware.deviceManager';
let dmClass;
let dmClass: deviceManager.DeviceManager;
function getDeviceManager() {
deviceManager.createDeviceManager('ohos.example.distributedService', (error, dm) => {
......@@ -100,9 +100,9 @@ function getDeviceManager() {
})
}
function getRemoteDeviceId() {
function getRemoteDeviceId(): string | undefined {
if (typeof dmClass === 'object' && dmClass != null) {
let list = dmClass.getTrustedDeviceListSync();
let list: Array<deviceManager.DeviceInfo> = dmClass.getTrustedDeviceListSync();
if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null");
return;
......@@ -111,6 +111,7 @@ function getRemoteDeviceId() {
return list[0].deviceId;
} else {
console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null");
return;
}
}
```
......@@ -123,15 +124,14 @@ function getRemoteDeviceId() {
```ts
import featureAbility from '@ohos.ability.featureAbility';
import Want from '@ohos.app.ability.Want';
function onStartRemoteAbility() {
console.info('onStartRemoteAbility begin');
let params;
let wantValue = {
let wantValue: Want = {
bundleName: 'ohos.samples.etsDemo',
abilityName: 'ohos.samples.etsDemo.RemoteAbility',
deviceId: getRemoteDeviceId(), // getRemoteDeviceId的定义在前面的示例代码中
parameters: params
};
console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue));
featureAbility.startAbility({
......
......@@ -8,17 +8,16 @@ ServiceAbility的启动与其他Ability并无区别,应用开发者可以在Pa
```ts
import featureAbility from '@ohos.ability.featureAbility'
import Want from '@ohos.app.ability.Want';
async function startServiceAbility() {
try {
console.info('Begin to start ability')
let param = {
want: {
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.ServiceAbility"
}
let want: Want = {
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.ServiceAbility"
}
await featureAbility.startAbility(param)
await featureAbility.startAbility({want})
console.info(`Start ability succeed`)
} catch (error) {
console.error('Start ability failed with ' + error)
......
......@@ -10,16 +10,18 @@
```ts
import featureAbility from '@ohos.ability.featureAbility';
let parameter = {
"want": {
bundleName: "com.ohos.stage",
abilityName: "EntryAbility"
import { BusinessError } from '@ohos.base';
featureAbility.startAbility(
{
want: {
bundleName: "com.ohos.stage",
abilityName: "EntryAbility"
}
}
};
featureAbility.startAbility(parameter).then((code) => {
).then((code) => {
console.info('Ability verify code: ' + JSON.stringify(code));
}).catch((error) => {
}).catch((error: BusinessError) => {
console.error("Ability failed: " + JSON.stringify(error));
});
```
......@@ -34,16 +36,17 @@ startAbilityForResult和startAbility的区别是当UIAbility销毁的时候会
```ts
import featureAbility from '@ohos.ability.featureAbility';
let parameter = {
"want": {
bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.EntryAbility"
}
};
featureAbility.startAbilityForResult(parameter).then((result) => {
import { BusinessError } from '@ohos.base';
featureAbility.startAbilityForResult(
{
want: {
bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.EntryAbility"
}
}).then((result) => {
console.info('Ability verify result: ' + JSON.stringify(result));
}).catch((error) => {
}).catch((error: BusinessError) => {
console.error("Ability failed: " + JSON.stringify(error));
});
```
......@@ -56,16 +59,18 @@ featureAbility.startAbilityForResult(parameter).then((result) => {
```ts
import particleAbility from '@ohos.ability.particleAbility';
let parameter = {
"want": {
bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.EntryAbility"
import { BusinessError } from '@ohos.base';
particleAbility.startAbility(
{
want: {
bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.EntryAbility"
}
}
};
particleAbility.startAbility(parameter).then(() => {
).then(() => {
console.info('Start Ability successfully.');
}).catch((error) => {
}).catch((error: BusinessError) => {
console.error("Ability failed: " + JSON.stringify(error));
});
```
......@@ -21,22 +21,24 @@
```ts
import common from '@ohos.app.ability.common';
import { Configuration } from '@ohos.app.ability.Configuration';
import EnvironmentCallback from '@ohos.app.ability.EnvironmentCallback';
@Entry
@Component
struct Index {
private context = getContext(this) as common.UIAbilityContext;
private callbackId: number; // 注册订阅系统环境变化的ID
private callbackId: number = 0; // 注册订阅系统环境变化的ID
subscribeConfigurationUpdate() {
let systemLanguage: string = this.context.config.language; // 获取系统当前语言
let systemLanguage: string | undefined = this.context.config.language; // 获取系统当前语言
// 1.获取ApplicationContext
let applicationContext = this.context.getApplicationContext();
// 2.通过applicationContext订阅环境变量变化
let environmentCallback = {
onConfigurationUpdated(newConfig) {
let environmentCallback: EnvironmentCallback = {
onConfigurationUpdated(newConfig: Configuration) {
console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
if (this.systemLanguage !== newConfig.language) {
......@@ -68,7 +70,7 @@
@Component
struct Index {
private context = getContext(this) as common.UIAbilityContext;
private callbackId: number; // 注册订阅系统环境变化的ID
private callbackId: number = 0; // 注册订阅系统环境变化的ID
unsubscribeConfigurationUpdate() {
let applicationContext = this.context.getApplicationContext();
......@@ -95,8 +97,9 @@
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
import { Configuration } from '@ohos.app.ability.Configuration';
let systemLanguage: string; // 系统当前语言
let systemLanguage: string | undefined; // 系统当前语言
export default class MyAbilityStage extends AbilityStage {
onCreate() {
......@@ -104,7 +107,7 @@ export default class MyAbilityStage extends AbilityStage {
console.info(`systemLanguage is ${systemLanguage} `);
}
onConfigurationUpdate(newConfig) {
onConfigurationUpdate(newConfig: Configuration) {
console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
if (systemLanguage !== newConfig.language) {
......@@ -127,16 +130,19 @@ UIAbility组件提供了`UIAbility.onConfigurationUpdate()`回调方法用于订
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
import { Configuration } from '@ohos.app.ability.Configuration';
let systemLanguage: string; // 系统当前语言
let systemLanguage: string | undefined; // 系统当前语言
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
systemLanguage = this.context.config.language; // UIAbility实例首次加载时,获取系统当前语言
console.info(`systemLanguage is ${systemLanguage} `);
}
onConfigurationUpdate(newConfig) {
onConfigurationUpdate(newConfig: Configuration) {
console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
if (systemLanguage !== newConfig.language) {
......@@ -145,7 +151,7 @@ export default class EntryAbility extends UIAbility {
}
}
...
// ...
}
```
......@@ -161,12 +167,13 @@ ExtensionAbility组件提供了`onConfigurationUpdate()`回调方法用于订阅
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import { Configuration } from '@ohos.app.ability.Configuration';
export default class EntryFormAbility extends FormExtensionAbility {
onConfigurationUpdate(newConfig) {
onConfigurationUpdate(newConfig: Configuration) {
console.info(`newConfig is ${JSON.stringify(newConfig)}`);
}
...
// ...
}
```
......@@ -4,7 +4,6 @@
基于OpenHarmony的应用模型,可以通过以下几种方式来实现UIAbility组件与UI之间的数据同步。
- [使用EventHub进行数据通信](#使用eventhub进行数据通信):在基类Context中提供了EventHub对象,可以通过发布订阅方式来实现事件的传递。在事件传递前,订阅者需要先进行订阅,当发布者发布事件时,订阅者将接收到事件并进行相应处理。
- [使用globalThis进行数据同步](#使用globalthis进行数据同步):在ArkTS引擎实例内部,globalThis是一个全局对象,可以被ArkTS引擎实例内的UIAbility组件、ExtensionAbility组件和ArkUI页面(Page)访问。
- [使用AppStorage/LocalStorage进行数据同步](#使用appstorage/localstorage进行数据同步):ArkUI提供了AppStorage和LocalStorage两种应用级别的状态管理方案,可用于实现应用级别和UIAbility级别的数据同步。
......@@ -18,21 +17,23 @@
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
const TAG: string = '[Example].[Entry].[EntryAbility]';
export default class EntryAbility extends UIAbility {
func1(...data) {
func1(data: string) {
// 触发事件,完成相应的业务操作
console.info(TAG, '1. ' + JSON.stringify(data));
}
onCreate(want, launch) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// 获取eventHub
let eventhub = this.context.eventHub;
// 执行订阅操作
eventhub.on('event1', this.func1);
eventhub.on('event1', (...data) => {
eventhub.on('event1', (data: string) => {
// 触发事件,完成相应的业务操作
console.info(TAG, '2. ' + JSON.stringify(data));
});
......@@ -84,229 +85,6 @@
this.context.eventHub.off('event1');
```
## 使用globalThis进行数据同步
globalThis是[ArkTS引擎实例](thread-model-stage.md)内部的一个全局对象,引擎内部的UIAbility/ExtensionAbility/Page都可以使用,因此可以使用globalThis对象进行数据同步。
**图1** 使用globalThis进行数据同步
![globalThis1](figures/globalThis1.png)
如上图所示,下面从如下三个场景和一个注意点来介绍globalThis的使用:
- [UIAbility和Page之间使用globalThis](#uiability和page之间使用globalthis)
- [UIAbility和UIAbility之间使用globalThis](#uiability和uiability之间使用globalthis)
- [UIAbility和ExtensionAbility之间使用globalThis](#uiability和extensionability之间使用globalthis)
- [globalThis使用的注意事项](#globalthis使用的注意事项)
### UIAbility和Page之间使用globalThis
通过在globalThis对象上绑定属性/方法,可以实现UIAbility组件与UI之间的数据同步。例如在UIAbility组件中绑定want参数,即可在UIAbility对应的UI上使用want参数信息。
1. 调用[`startAbility()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动一个UIAbility实例时,被启动的UIAbility创建完成后会进入[`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)生命周期回调,且在[`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)生命周期回调中能够接受到传递过来的want参数,可以将want参数绑定到globalThis上。
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onCreate(want, launch) {
globalThis.entryAbilityWant = want;
...
}
...
}
```
2. 在UI中即可通过globalThis获取到want参数信息。
```ts
let entryAbilityWant;
@Entry
@Component
struct Index {
aboutToAppear() {
entryAbilityWant = globalThis.entryAbilityWant;
}
// 页面展示
build() {
...
}
}
```
### UIAbility和UIAbility之间使用globalThis
在同一个应用中,UIAbility与UIAbility之间的数据传递可以通过将数据绑定到全局变量globalThis上进行同步。例如,在UIAbilityA中将数据保存在globalThis对象中,然后跳转到UIAbilityB中就可以获取该数据。
1. UIAbilityA中保存数据一个字符串数据并挂载到globalThis上。
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
export default class UIAbilityA extends UIAbility {
onCreate(want, launch) {
globalThis.entryAbilityStr = 'UIAbilityA'; // UIAbilityA存放字符串“UIAbilityA”到globalThis
...
}
}
```
2. UIAbilityB中获取对应的数据。
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
export default class UIAbilityB extends UIAbility {
onCreate(want, launch) {
// UIAbilityB从globalThis读取name并输出
console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr);
...
}
}
```
### UIAbility和ExtensionAbility之间使用globalThis
在同一个应用中,UIAbility和ExtensionAbility之间的数据传递也可以通过将数据绑定到全局变量globalThis上进行同步。例如,在UIAbilityA中保存数据,在ServiceExtensionAbility中就可以获取该数据。
1. UIAbilityA中保存数据一个字符串数据并挂载到globalThis上。
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
export default class UIAbilityA extends UIAbility {
onCreate(want, launch) {
// UIAbilityA存放字符串“UIAbilityA”到globalThis
globalThis.entryAbilityStr = 'UIAbilityA';
...
}
}
```
2. ExtensionAbility中获取数据。
```ts
import Extension from '@ohos.app.ability.ServiceExtensionAbility'
export default class ServiceExtAbility extends Extension {
onCreate(want) {
// ServiceExtAbility从globalThis读取name并输出
console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr);
...
}
}
```
### globalThis使用的注意事项
**图2** globalThis注意事项
![globalThis2](figures/globalThis2.png)
- Stage模型下进程内的UIAbility组件共享ArkTS引擎实例,使用globalThis时需要避免存放相同名称的对象。例如UIAbilityA和UIAbilityB可以使用globalThis共享数据,在存放相同名称的对象时,先存放的对象会被后存放的对象覆盖。
- globalThis不支持跨进程使用,不同进程的UIAbility组件和ExtensionAbility组件无法使用globalThis共享数据,进程模型及进程间通信机制见[进程模型概述](./process-model-stage.md#进程模型概述)
- FA模型因为每个UIAbility组件之间引擎隔离,不会存在该问题。
- 对于绑定在globalThis上的对象,其生命周期与ArkTS虚拟机实例相同,建议在使用完成之后将其赋值为null,以减少对应用内存的占用。
Stage模型上同名对象覆盖导致问题的场景举例说明。
1. 在UIAbilityA文件中使用globalThis中存放了[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md)
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
export default class UIAbilityA extends UIAbility {
onCreate(want, launch) {
globalThis.context = this.context; // UIAbilityA存放context到globalThis
...
}
}
```
2. 在UIAbilityA的页面中获取该[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md)并进行使用。使用完成后将UIAbilityA实例切换至后台。
```ts
@Entry
@Component
struct Index {
onPageShow() {
let ctx = globalThis.context; // 页面中从globalThis中取出context并使用
}
// 页面展示
build() {
...
}
}
```
3. 在UIAbilityB文件中使用globalThis中存放了[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md),并且命名为相同的名称。
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
export default class UIAbilityB extends UIAbility {
onCreate(want, launch) {
// UIAbilityB覆盖了UIAbilityA在globalThis中存放的context
globalThis.context = this.context;
...
}
}
```
4. 在UIAbilityB的页面中获取该[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md)并进行使用。此时获取到的globalThis.context已经表示为UIAbilityB中赋值的[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md)内容。
```ts
@Entry
@Component
struct Index {
onPageShow() {
let ctx = globalThis.context; // Page中从globalThis中取出context并使用
}
// 页面展示
build() {
...
}
}
```
5. 在UIAbilityB实例切换至后台,将UIAbilityA实例从后台切换回到前台。此时UIAbilityA的onCreate生命周期不会再次进入。
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
export default class UIAbilityA extends UIAbility {
onCreate(want, launch) { // UIAbilityA从后台进入前台,不会再走这个生命周期
globalThis.context = this.context;
...
}
}
```
6. 在UIAbilityA的页面再次回到前台时,其获取到的globalThis.context表示的为UIAbilityB的[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md),而不是UIAbilityA的[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md),在UIAbilityA的页面中使用则会出错。
```ts
@Entry
@Component
struct Index {
onPageShow() {
let ctx = globalThis.context; // 这时候globalThis中的context是UIAbilityB的context
}
// 页面展示
build() {
...
}
}
```
## 使用AppStorage/LocalStorage进行数据同步
ArkUI提供了AppStorage和LocalStorage两种应用级别的状态管理方案,可用于实现应用级别和UIAbility级别的数据同步。使用这些方案可以方便地管理应用状态,提高应用性能和用户体验。其中,AppStorage是一个全局的状态管理器,适用于多个UIAbility共享同一状态数据的情况;而LocalStorage则是一个局部的状态管理器,适用于单个UIAbility内部使用的状态数据。通过这两种方案,开发者可以更加灵活地控制应用状态,提高应用的可维护性和可扩展性。详细请参见[应用级变量的状态管理](../quick-start/arkts-application-state-management-overview.md)
......@@ -31,8 +31,12 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
1. 在EntryAbility中,通过调用[`startAbility()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动UIAbility,[want](../reference/apis/js-apis-app-ability-want.md)为UIAbility实例启动的入口参数,其中bundleName为待启动应用的Bundle名称,abilityName为待启动的Ability名称,moduleName在待启动的UIAbility属于不同的Module时添加,parameters为自定义信息参数。示例中的context的获取方式请参见[获取UIAbility的上下文信息](uiability-usage.md#获取uiability的上下文信息)
```ts
let context = ...; // UIAbilityContext
let want = {
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
let context: common.UIAbilityContext = ...; // UIAbilityContext
let want: Want = {
deviceId: '', // deviceId为空表示本设备
bundleName: 'com.example.myapplication',
moduleName: 'func', // moduleName非必选
......@@ -44,7 +48,7 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
// context为调用方UIAbility的UIAbilityContext
context.startAbility(want).then(() => {
console.info('Succeeded in starting ability.');
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -53,13 +57,15 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class FuncAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// 接收调用方UIAbility传过来的参数
let funcAbilityWant = want;
let info = funcAbilityWant?.parameters?.info;
...
// ...
}
}
```
......@@ -71,7 +77,9 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
3. 在FuncAbility业务完成之后,如需要停止当前UIAbility实例,在FuncAbility中通过调用[`terminateSelf()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself)方法实现。
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
let context: common.UIAbilityContext = ...; // UIAbilityContext
// context为需要停止的UIAbility实例的AbilityContext
context.terminateSelf((err) => {
......@@ -96,8 +104,12 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
1. 在EntryAbility中,调用[`startAbilityForResult()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口启动FuncAbility,异步回调中的data用于接收FuncAbility停止自身后返回给EntryAbility的信息。示例中的context的获取方式请参见[获取UIAbility的上下文信息](uiability-usage.md#获取uiability的上下文信息)
```ts
let context = ...; // UIAbilityContext
let want = {
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
let context: common.UIAbilityContext = ...; // UIAbilityContext
let want: Want = {
deviceId: '', // deviceId为空表示本设备
bundleName: 'com.example.myapplication',
moduleName: 'func', // moduleName非必选
......@@ -108,8 +120,8 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
}
// context为调用方UIAbility的UIAbilityContext
context.startAbilityForResult(want).then((data) => {
...
}).catch((err) => {
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -117,9 +129,12 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
2. 在FuncAbility停止自身时,需要调用[`terminateSelfWithResult()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)方法,入参abilityResult为FuncAbility需要返回给EntryAbility的信息。
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
let context: common.UIAbilityContext = ...; // UIAbilityContext
const RESULT_CODE: number = 1001;
let abilityResult = {
let abilityResult: common.AbilityResult = {
resultCode: RESULT_CODE,
want: {
bundleName: 'com.example.myapplication',
......@@ -142,19 +157,23 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
3. FuncAbility停止自身后,EntryAbility通过[`startAbilityForResult()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)方法回调接收被FuncAbility返回的信息,RESULT_CODE需要与前面的数值保持一致。
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
let context: common.UIAbilityContext = ...; // UIAbilityContext
const RESULT_CODE: number = 1001;
...
// ...
// context为调用方UIAbility的UIAbilityContext
context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) {
// 解析被调用方UIAbility返回的信息
let info = data.want?.parameters?.info;
...
// ...
}
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -201,8 +220,12 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
2. 在调用方want参数中的entities和action需要被包含在待匹配UIAbility的skills配置的entities和actions中。系统匹配到符合entities和actions参数条件的UIAbility后,会弹出选择框展示匹配到的UIAbility实例列表供用户选择使用。示例中的context的获取方式请参见[获取UIAbility的上下文信息](uiability-usage.md#获取uiability的上下文信息)
```ts
let context = ...; // UIAbilityContext
let want = {
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
let context: common.UIAbilityContext = ...; // UIAbilityContext
let want: Want = {
deviceId: '', // deviceId为空表示本设备
// uncomment line below if wish to implicitly query only in the specific bundle.
// bundleName: 'com.example.myapplication',
......@@ -214,7 +237,7 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
// context为调用方UIAbility的UIAbilityContext
context.startAbility(want).then(() => {
console.info('Succeeded in starting ability.');
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -225,7 +248,9 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
3. 在文档应用使用完成之后,如需要停止当前UIAbility实例,通过调用[`terminateSelf()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself)方法实现。
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
let context: common.UIAbilityContext = ...; // UIAbilityContext
// context为需要停止的UIAbility实例的AbilityContext
context.terminateSelf((err) => {
......@@ -270,8 +295,12 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
2. 调用方使用[`startAbilityForResult()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)方法启动支付应用的UIAbility,在调用方want参数中的entities和action需要被包含在待匹配UIAbility的skills标签配置的entities和actions中。异步回调中的data用于后续接收支付UIAbility停止自身后返回给调用方的信息。系统匹配到符合entities和actions参数条件的UIAbility后,会弹出选择框展示匹配到的UIAbility实例列表供用户选择使用。
```ts
let context = ...; // UIAbilityContext
let want = {
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
let context: common.UIAbilityContext = ...; // UIAbilityContext
let want:Want = {
deviceId: '', // deviceId为空表示本设备
// uncomment line below if wish to implicitly query only in the specific bundle.
// bundleName: 'com.example.myapplication',
......@@ -282,8 +311,8 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
// context为调用方UIAbility的UIAbilityContext
context.startAbilityForResult(want).then((data) => {
...
}).catch((err) => {
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -291,9 +320,12 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
3. 在支付UIAbility完成支付之后,需要调用[`terminateSelfWithResult()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)方法实现停止自身,并将abilityResult参数信息返回给调用方。
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
let context: common.UIAbilityContext = ...; // UIAbilityContext
const RESULT_CODE: number = 1001;
let abilityResult = {
let abilityResult: common.AbilityResult = {
resultCode: RESULT_CODE,
want: {
bundleName: 'com.example.funcapplication',
......@@ -316,10 +348,14 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
4. 在调用方[`startAbilityForResult()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)方法回调中接收支付应用返回的信息,RESULT_CODE需要与前面[`terminateSelfWithResult()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)返回的数值保持一致。
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
let context: common.UIAbilityContext = ...; // UIAbilityContext
const RESULT_CODE: number = 1001;
let want = {
let want: Want = {
// Want参数信息
};
......@@ -328,9 +364,9 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
if (data?.resultCode === RESULT_CODE) {
// 解析被调用方UIAbility返回的信息
let payResult = data.want?.parameters?.payResult;
...
// ...
}
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -361,9 +397,13 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳
```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import StartOptions from '@ohos.app.ability.StartOptions';
import { BusinessError } from '@ohos.base';
let context = ...; // UIAbilityContext
let want = {
let context: common.UIAbilityContext = ...; // UIAbilityContext
let want: Want = {
deviceId: '', // deviceId为空表示本设备
bundleName: 'com.example.myapplication',
moduleName: 'func', // moduleName非必选
......@@ -372,13 +412,13 @@ let want = {
info: '来自EntryAbility Index页面',
},
}
let options = {
let options: StartOptions = {
windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING
};
// context为调用方UIAbility的UIAbilityContext
context.startAbility(want, options).then(() => {
console.info('Succeeded in starting ability.');
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -397,8 +437,12 @@ context.startAbility(want, options).then(() => {
```ts
let context = ...; // UIAbilityContext
let want = {
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
let context: common.UIAbilityContext = ...; // UIAbilityContext
let want: Want = {
deviceId: '', // deviceId为空表示本设备
bundleName: 'com.example.funcapplication',
moduleName: 'entry', // moduleName非必选
......@@ -410,7 +454,7 @@ let want = {
// context为调用方UIAbility的UIAbilityContext
context.startAbility(want).then(() => {
console.info('Succeeded in starting ability.');
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -428,7 +472,7 @@ import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
export default class FuncAbility extends UIAbility {
funcAbilityWant: Want;
funcAbilityWant: Want | undefined = undefined;
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// 接收调用方UIAbility传过来的参数
......@@ -442,7 +486,7 @@ export default class FuncAbility extends UIAbility {
url = 'pages/Second';
}
windowStage.loadContent(url, (err, data) => {
...
// ...
});
}
}
......@@ -490,14 +534,14 @@ S-->>U: 显示给张三发短信的页面
import { Router, UIContext } from '@ohos.arkui.UIContext';
export default class EntryAbility extends UIAbility {
funcAbilityWant: Want;
uiContext: UIContext;
funcAbilityWant: Want | undefined = undefined;
uiContext: UIContext | undefined = undefined;
...
// ...
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
...
// ...
let windowClass: window.Window;
windowStage.getMainWindow((err, data) => {
......@@ -515,9 +559,11 @@ S-->>U: 显示给张三发短信的页面
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 { BusinessError } from '@ohos.base';
export default class EntryAbility extends UIAbility {
funcAbilityWant: Want;
uiContext: UIContext;
funcAbilityWant: Want | undefined = undefined;
uiContext: UIContext | undefined = undefined;
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
if (want?.parameters?.router && want.parameters.router === 'funcA') {
......@@ -525,13 +571,13 @@ S-->>U: 显示给张三发短信的页面
let router: Router = this.uiContext.getRouter();
router.pushUrl({
url: funcAUrl
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to push url. Code is ${err.code}, message is ${err.message}`);
})
}
}
...
// ...
}
```
......@@ -629,7 +675,7 @@ Call功能主要接口如下表所示。具体的API详见[接口文档](../refe
num: number = 0;
str: string = '';
constructor(num, string) {
constructor(num: number, string: string) {
this.num = num;
this.str = string;
}
......@@ -654,10 +700,12 @@ Call功能主要接口如下表所示。具体的API详见[接口文档](../refe
```ts
import rpc from '@ohos.rpc';
const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg';
function sendMsgCallback(data) {
function sendMsgCallback(data: rpc.MessageSequence) {
console.info('CalleeSortFunc called');
// 获取Caller发送的序列化数据
......@@ -671,7 +719,7 @@ Call功能主要接口如下表所示。具体的API详见[接口文档](../refe
}
export default class CalleeAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
} catch (err) {
......@@ -703,32 +751,39 @@ Call功能主要接口如下表所示。具体的API详见[接口文档](../refe
```ts
// 注册caller的release监听
private regOnRelease(caller) {
try {
caller.on('release', (msg) => {
console.info(`caller onRelease is called ${msg}`);
})
console.info('Succeeded in registering on release.');
} catch (err) {
console.err(`Failed to caller register on release. Code is ${err.code}, message is ${err.message}`);
import UIAbility from '@ohos.app.ability.UIAbility';
import { Caller } from '@ohos.app.ability.UIAbility';
export default class CallerAbility extends UIAbility {
caller: Caller | undefined = undefined;
// 注册caller的release监听
private regOnRelease(caller: Caller) {
try {
caller.on('release', (msg: string) => {
console.info(`caller onRelease is called ${msg}`);
})
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}`);
}
}
}
async onButtonGetCaller() {
try {
this.caller = await context.startAbilityByCall({
bundleName: 'com.samples.CallApplication',
abilityName: 'CalleeAbility'
});
if (this.caller === undefined) {
console.info('get caller failed')
return;
async onButtonGetCaller() {
try {
this.caller = await context.startAbilityByCall({
bundleName: 'com.samples.CallApplication',
abilityName: 'CalleeAbility'
});
if (this.caller === undefined) {
console.info('get caller failed')
return;
}
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}`);
}
console.info('get caller success')
this.regOnRelease(this.caller)
} (err) {
console.err(`Failed to get caller. Code is ${err.code}, message is ${err.message}`);
}
}
```
......
......@@ -95,12 +95,16 @@ specified启动模式为指定实例模式,针对一些特殊场景使用(
```ts
// 在启动指定实例模式的UIAbility时,给每一个UIAbility实例配置一个独立的Key标识
// 例如在文档使用场景中,可以用文档路径作为Key标识
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
function getInstance() {
...
return 'key';
}
let context = ...; // context为调用方UIAbility的UIAbilityContext
let want = {
let context:common.UIAbilityContext = ...; // context为调用方UIAbility的UIAbilityContext
let want: Want = {
deviceId: '', // deviceId为空表示本设备
bundleName: 'com.example.myapplication',
abilityName: 'SpecifiedAbility',
......@@ -112,7 +116,7 @@ specified启动模式为指定实例模式,针对一些特殊场景使用(
context.startAbility(want).then(() => {
console.info('Succeeded in starting ability.');
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`);
})
```
......@@ -123,9 +127,10 @@ specified启动模式为指定实例模式,针对一些特殊场景使用(
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
import Want from '@ohos.app.ability.Want';
export default class MyAbilityStage extends AbilityStage {
onAcceptWant(want): string {
onAcceptWant(want: Want): string {
// 在被调用方的AbilityStage中,针对启动模式为specified的UIAbility返回一个UIAbility实例对应的一个Key值
// 当前示例指的是module1 Module的SpecifiedAbility
if (want.abilityName === 'SpecifiedAbility') {
......
......@@ -21,12 +21,14 @@ Create状态为在应用加载过程中,UIAbility实例创建完成时触发
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// 应用初始化
}
...
// ...
}
```
......@@ -46,7 +48,7 @@ import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
...
// ...
onWindowStageCreate(windowStage: window.WindowStage) {
// 设置WindowStage的事件订阅(获焦/失焦、可见/不可见)
......@@ -77,7 +79,7 @@ export default class EntryAbility extends UIAbility {
// 设置UI加载
windowStage.loadContent('pages/Index', (err, data) => {
...
// ...
});
}
}
......@@ -96,11 +98,11 @@ import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
windowStage: window.WindowStage;
...
// ...
onWindowStageCreate(windowStage: window.WindowStage) {
this.windowStage = windowStage;
...
// ...
}
onWindowStageDestroy() {
......@@ -133,7 +135,7 @@ Foreground和Background状态分别在UIAbility实例切换至前台和切换至
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
...
// ...
onForeground() {
// 申请系统需要的资源,或者重新申请在onBackground()中释放的资源
......@@ -157,7 +159,7 @@ Destroy状态在UIAbility实例销毁时触发。可以在onDestroy()回调中
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
...
// ...
onDestroy() {
// 系统资源的释放、数据的保存等
......
......@@ -17,11 +17,11 @@ export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
windowStage.loadContent('pages/Index', (err, data) => {
...
// ...
});
}
...
// ...
}
```
......@@ -37,9 +37,11 @@ UIAbility类拥有自身的上下文信息,该信息为[UIAbilityContext](../r
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// 获取UIAbility实例的上下文
let context = this.context;
...
......@@ -51,6 +53,7 @@ UIAbility类拥有自身的上下文信息,该信息为[UIAbilityContext](../r
```ts
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
@Entry
@Component
......@@ -58,7 +61,7 @@ UIAbility类拥有自身的上下文信息,该信息为[UIAbilityContext](../r
private context = getContext(this) as common.UIAbilityContext;
startAbilityTest() {
let want = {
let want: Want = {
// Want参数信息
};
this.context.startAbility(want);
......@@ -76,6 +79,7 @@ UIAbility类拥有自身的上下文信息,该信息为[UIAbilityContext](../r
```ts
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
@Entry
@Component
......@@ -83,7 +87,7 @@ UIAbility类拥有自身的上下文信息,该信息为[UIAbilityContext](../r
startAbilityTest() {
let context = getContext(this) as common.UIAbilityContext;
let want = {
let want: Want = {
// Want参数信息
};
context.startAbility(want);
......
......@@ -18,7 +18,9 @@
显式Want通常用于在当前应用中启动已知的目标应用组件,通过提供目标应用组件所在应用的Bundle名称信息(bundleName)并在Want对象内指定abilityName来启动目标应用组件。当有明确处理请求的对象时,显式Want是一种简单有效的启动目标应用组件的方式。
```ts
let wantInfo = {
import Want from '@ohos.app.ability.Want';
let wantInfo: Want = {
deviceId: '', // deviceId为空表示本设备
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
......@@ -31,7 +33,9 @@
```ts
let wantInfo = {
import Want from '@ohos.app.ability.Want';
let wantInfo: Want = {
// uncomment line below if wish to implicitly query only in the specific bundle.
// bundleName: 'com.example.myapplication',
action: 'ohos.want.action.search',
......
......@@ -37,10 +37,12 @@ WindowExtensionAbility提供了onConnect()、onDisconnect()和onWindowReady()生
3. 打开WindowExtAbility.ts文件,导入WindowExtensionAbility的依赖包,自定义类继承WindowExtensionAbility并实现onWindowReady()、onConnect()和onDisconnect()生命周期回调。
```ts
import Extension from '@ohos.application.WindowExtensionAbility'
import Extension from '@ohos.application.WindowExtensionAbility'
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
export default class WindowExtAbility extends Extension {
onWindowReady(window) {
onWindowReady(window: window.Window) {
window.loadContent('WindowExtAbility/pages/index1').then(() => {
window.getProperties().then((pro) => {
console.info("WindowExtension " + JSON.stringify(pro));
......@@ -49,11 +51,11 @@ WindowExtensionAbility提供了onConnect()、onDisconnect()和onWindowReady()生
})
}
onConnect(want) {
onConnect(want: Want) {
console.info('JSWindowExtension onConnect ' + want.abilityName);
}
onDisconnect(want) {
onDisconnect(want: Want) {
console.info('JSWindowExtension onDisconnect ' + want.abilityName);
}
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册