当前位置:网站首页>【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability
【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability
2022-08-03 04:42:00 【Huawei Developer Forum】
今天学习一下怎么实现启动一个Ability文档讲解,主要分为“参考资料”“api讲解”,“运行效果”三个部分讲解,
1.参考资料
参考资料启动一个Ability
2.Api讲解
startAbility
参数
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
parameter | StartAbilityParameter | 是 | 启动参数. |
返回值
类型 | 说明 |
---|---|
Promise | Promise形式返回启动结果.错误码参考 StartAbilityCode |
示例
var str = {
"want": {
"deviceId": "",
"bundleName": "",
"abilityName": "",
"uri": "",
"type": "image/*",
"options": {},
"action": "",
"parameters": {},
"entities": [
"entity.com.example.mytest.ENTITIES"
]
},
"abilityStartSetting": {}
};
featureAbility.startAbility(str)
.then((data) => {
console.info('Operation successful. Data: ' + JSON.stringify(data))
}).catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
})
featureAbility.startAbilityForResult
startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback): void
以异步方法启动Ability并在结束的时候返回执行结果,使用callback形式返回结果.
参数:
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
parameter | StartAbilityParameter | 是 | 启动参数. |
callback | AsyncCallback | 是 | callback形式返回结果 |
示例
var str = {
"want": {
"deviceId": "",
"bundleName": "",
"abilityName": "",
"uri": "",
"type": "",
"action": "",
"parameters": {},
"entities": [
"entity.com.example.mytest.ENTITIES"
]
},
"abilityStartSetting": {}
};
featureAbility.startAbilityForResult(str, (error, data) => {
if (error) {
console.error('Operation failed. Cause: ' + error);
return;
}
console.info('Operation succeeded: ' + data);
});
补充说明
StartAbilityParameter
启动Ability所需参数.
名称 | 参数类型 | 可读 | 可写 | 说明 |
---|---|---|---|---|
want | Want | 是 | 是 | 启动Ability的want信息. |
abilityStartSetting | {[key: string]: any} | 是 | 是 | 表示能力的特殊属性,当开发者启动能力时,该属性可以作为调用中的输入参数传递. |
taskSyncAnimationOptions | TaskSyncAnimationOptions | 是 | 是 | 启动Ability时需要进行动画控制的特殊属性,当开发者希望控制启动Ability的动画时,请传入该参数,需要权限ohos.permission.CONTROL_TASK_SYNC_ANIMATOR. |
Want
启动信息.
名称 | 参数类型 | 可读 | 可写 | 说明 |
---|---|---|---|---|
deviceId | string | 是 | 是 | 表示运行指定Ability的设备ID. |
bundleName | string | 是 | 是 | 表示包描述.如果在Want中同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability. |
abilityName | string | 是 | 是 | 表示待启动的Ability名称.如果在Want中同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability. |
uri | string | 是 | 是 | 表示Uri描述.如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息. |
type | string | 是 | 是 | 表示MIME type类型描述,比如:“text/plain” 、 "image/*"等. |
action | string | 是 | 是 | 表示action选项描述.具体参考:Action使用时通过wantConstant.Action获取,示例:wantConstant.Action.ACTION_HOME. |
entities | Array | 是 | 是 | 表示entities相关描述.具体参考:Entity使用时通过wantConstant.Entity获取,示例:wantConstant.Entity.ENTITY_DEFAULT. |
flags | number | 是 | 是 | 表示处理Want的方式.默认传数字,具体参考:Flags使用时通过wantConstant.Flags获取,示例:wantConstant.Flags.FLAG_INSTALL_ON_DEMAND. |
parameters | {[key: string]: any} | 是 | 是 | 表示WantParams描述. |
3.运行效果
3.1准备阶段
在新建OnceAbility和TwoAbility两个Ability界面,如下图示所示,包名为“com.harmony.alliance.myapplication”
config.json文件
2.在Index.ets写两个按钮“startAbility启动OnceAbility并传参”和“startAbilityForResult跳转TwoAbility”,代码如下
import featureAbility from '@ohos.ability.featureAbility';
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('startAbility启动OnceAbility并传参')
.fontSize(50)
.fontWeight(FontWeight.Bold)
Text('startAbilityForResult跳转TwoAbility')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.backgroundColor(Color.Red)
}
.width('100%')
.height('100%')
}
}
效果如图所示
3.2实现“startAbility启动OnceAbility并传参”
ets 实现点击按钮功能,代码如下
bundleName:就是config.json的bundleName,
abilityName就是ability的名称,
parameters:作为传递的参数
在OnceAbilitySlice使用如下代码进行接收
Intent intent1= getAbility().getIntent();
IntentParams myIntentParams= intent1.getParams();
myIntentParams.getParam("key1")
public startOnceAbility(){
var str = {
"want": {
"deviceId": "",
"bundleName": "com.harmony.alliance.myapplication",
"abilityName": "OnceAbility",
"uri": "",
"action": "",
"parameters":{key1:"value1",key2:"value2"}
},
};
featureAbility.startAbility(str)
.then((data) => {
console.info('Operation successful. Data: ' + JSON.stringify(data))
}).catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
})
}
OnceAbilitySlice的xml文件
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:background_element="#ed6262"
ohos:orientation="vertical">
<Text
ohos:top_margin="20vp"
ohos:id="$+id:text_helloworld"
ohos:height="200vp"
ohos:width="match_content"
ohos:layout_alignment="horizontal_center"
ohos:text="这是OnceAbility"
ohos:text_size="40vp"
/>
<Text
ohos:id="$+id:mTvResult"
ohos:height="200vp"
ohos:width="match_parent"
ohos:text="参数:"
ohos:multiple_lines="true"
ohos:text_size="40vp"
ohos:padding="10fp"
ohos:background_element="#ffffff"/>
</DirectionalLayout>
效果如下
onceAbilitySlice代码如下
package com.harmony.alliance.myapplication.slice;
import com.harmony.alliance.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.agp.components.Text;
public class OnceAbilitySlice extends AbilitySlice {
Text mTvResult;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_once);
Intent intent1= getAbility().getIntent();
IntentParams myIntentParams= intent1.getParams();
mTvResult=findComponentById(ResourceTable.Id_mTvResult);
mTvResult.setText("参数:"+"key1"+"===>"+myIntentParams.getParam("key1")+
"\n key2:"+"===>"+myIntentParams.getParam("key2"));
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
3.3实现“startAbility启动OnceAbility并传参”
ets实现“startAbilityForResult跳转TwoAbility”ets代码如下
public startTwoAbility(){
var str = {
"want": {
"deviceId": "",
"bundleName": "com.harmony.alliance.myapplication",
"abilityName": "TwoAbility",
"uri": "",
"type": "",
"action": "",
},
"abilityStartSetting": {}
};
featureAbility.startAbilityForResult(str, (error, data) => {
if (error) {
console.error('Operation failed. Cause: ' + error);
return;
}
console.info('Operation succeeded: ' + JSON.stringify(data));
});
}
twoAbilitySlice的xml代码如下
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="vertical">
<Text
ohos:id="$+id:text_helloworld"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_ability_two"
ohos:layout_alignment="horizontal_center"
ohos:text="关闭并回传数据"
ohos:text_size="40vp"
/>
</DirectionalLayout>
效果图如下
TwoabilitySlice的代码如下
package com.harmony.alliance.myapplication.slice;
import com.harmony.alliance.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
public class TwoAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_two);
findComponentById(ResourceTable.Id_text_helloworld).setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
Intent intent1 = new Intent();
intent1.setParam("key", "value");
getAbility().setResult(1001, intent1);
terminateAbility();
}
});
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
ets全部代码如下
import featureAbility from '@ohos.ability.featureAbility';
@Entry
@Component
struct Index {
public startOnceAbility(){
var str = {
"want": {
"deviceId": "",
"bundleName": "com.harmony.alliance.myapplication",
"abilityName": "OnceAbility",
"uri": "",
"action": "",
"parameters":{key1:"value1",key2:"value2"}
},
};
featureAbility.startAbility(str)
.then((data) => {
console.info('Operation successful. Data: ' + JSON.stringify(data))
}).catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
})
}
public startTwoAbility(){
var str = {
"want": {
"deviceId": "",
"bundleName": "com.harmony.alliance.myapplication",
"abilityName": "TwoAbility",
"uri": "",
"type": "",
"action": "",
},
"abilityStartSetting": {}
};
featureAbility.startAbilityForResult(str, (error, data) => {
if (error) {
console.error('Operation failed. Cause: ' + error);
return;
}
console.info('Operation succeeded: ' + JSON.stringify(data));
});
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('startAbility启动OnceAbility并传参')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(this.startOnceAbility.bind(this))
Text('startAbilityForResult跳转TwoAbility')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(this.startTwoAbility.bind(this))
.backgroundColor(Color.Red)
}
.width('100%')
.height('100%')
}
}
运行效果如下
欲了解更多更全技术文章,欢迎访问:https://developer.huawei.com/consumer/cn/forum/topic/0201822289188980017?fid=0102683795438680754?ha_source=zzh |
边栏推荐
- Secondary development of WinForm controls
- 刚上线就狂吸70W粉,新型商业模式“分享购”来了,你知道吗?
- 11.机器学习基础:机器学习的四个分支
- 修饰生物素DIAZO-生物素-PEG3-DBCO|重氮-生物素-三聚乙二醇-二苯基环辛炔
- Two ways to simulate multi-user login in Jmeter
- typescript46-函数之间的类型兼容性
- OpenFOAM extracts equivalency and calculates area
- 【Harmony OS】【ARK UI】轻量级数据存储
- 自组织是管理者和成员的双向奔赴
- [Harmony OS] [ARK UI] ETS context basic operations
猜你喜欢
多肽介导PEG磷脂——靶向功能材料之DSPE-PEG-RGD/TAT/NGR/APRPG
How to prepare for the test interface test data
如何利用 Flutter 实现炫酷的 3D 卡片和帅气的 360° 展示效果
Peptides mediated PEG DSPE of phospholipids, targeted functional materials - PEG - RGD/TAT/NGR/APRPG
MCM box model modeling method and source analysis of atmospheric O3
[Harmony OS] [ARK UI] ETS context basic operations
8.电影评论分类:二分类问题
Problems that need to be solved for interrupting the system
「短视频+社交电商」营销模式爆发式发展,带来的好处有什么?
Concepts and Methods of Exploratory Testing
随机推荐
JS底层手写
Live | StarRocks technology insider: low base dictionary global optimization
【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
获取Ip工具类
12.机器学习基础:评估机器学习模型
Test drive: project management module - curd development project
【Harmony OS】【ARK UI】ets使用startAbility或startAbilityForResult方式调起Ability
Shell条件语句判断
Bubble sort in c language structure
Shenzhen Offline Registration|StarRocks on AWS: How to conduct rapid and unified analysis of real-time data warehouses
接口测试 Mock 实战(二) | 结合 jq 完成批量化的手工 Mock
社交电商:流量红利已尽,裂变营销是最低成本的获客之道
Interface test Mock combat (2) | Combined with jq to complete batch manual Mock
刚上线就狂吸70W粉,新型商业模式“分享购”来了,你知道吗?
记录一些遇见的bug——mapstruct和lombok同时使用时,转换实体类时数据丢失问题
js garbage collection mechanism
Shell之条件语句
【开发者必看】【push kit】推送服务服务典型问题合集2
常见亲脂性细胞膜染料DiO, Dil, DiR, Did光谱图和实验操作流程
Interface test framework combat (1) | Requests and interface request construction