今天学习一下怎么实现启动一个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));
})

arkts比java速度快吗_bundle

 

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);
});

arkts比java速度快吗_bundle

补充说明

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”

arkts比java速度快吗_arkts比java速度快吗_03


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%')
  }
}

arkts比java速度快吗_bundle

效果如图所示

arkts比java速度快吗_JSON_05


3.2实现“startAbility启动OnceAbility并传参”

ets 实现点击按钮功能,代码如下

bundleName:就是config.json的bundleName,

abilityName就是ability的名称

parameters:作为传递的参数

在OnceAbilitySlice使用如下代码进行接收

Intent intent1=  getAbility().getIntent();
IntentParams myIntentParams= intent1.getParams();
myIntentParams.getParam("key1")

arkts比java速度快吗_bundle

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));
    })
  }

arkts比java速度快吗_bundle

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>

arkts比java速度快吗_bundle

效果如下

arkts比java速度快吗_Text_09


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);
    }

arkts比java速度快吗_bundle

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));
    });
  }

arkts比java速度快吗_bundle

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>

arkts比java速度快吗_bundle

效果图如下

arkts比java速度快吗_arkts比java速度快吗_13


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);
    }
}

arkts比java速度快吗_bundle

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%')
  }
}

arkts比java速度快吗_bundle

运行效果如下

arkts比java速度快吗_arkts比java速度快吗_16