其他分享
首页 > 其他分享> > CH4-armonyOS核心概念

CH4-armonyOS核心概念

作者:互联网

文章目录

前言

一个典型的HarmonyOS应用应该有与用户交互的界面,完成应用功能的业务逻辑和需要处理的业务数据。简单来说就是用户通过应用看到什么,通过应用能做什么以及对什么东西做。当然,对于一个复杂应用,不会只有一个可视化页面,会包含承载很多功能的显示处理模块,这些功能模块需要进行跳转切换。

目标

1.Ability概念

Ability的分类

20220116093412

2.Page Ability

2.1 Page与AbilitySlice

2.2 Page Ability应用场景

20220116124100

2.3 AbilitySlice路由配置

setMainRoute&addActionRoute

public class MyAbility extends Ability {
@Override
    public void onStart(Intent intent){
        super.onStart(intent); 		    
		setMainRoute(MainSlice.class.getName());
        addActionRoute("action.paybyAlipay",PayAlipaySlice.class.getName());
   	 	addActionRoute("action.paybyWechat",PayWechatSlice.class.getName());
    }
}

20220116124638

注册action

. addActionRoute()方法中使用的动作命名,需要在应用配置文件( config.json )中注册

{
    "module": {
        "abilities": [
        	{
                "skills":[
                    {
                        "actions":[
                            "action.paybyAlipay",
                            "action.paybyWechat"
                        ]
                    }
                ]
                ………
            }
        ]
    .. 
    }...
}
lntent intent = new Intent();
Operation operation = new lntent.OperationBuilder().withAction("action.paybyAlipay").build();
intent.setOperation(operation);
startAbility (intent);

2.4 Page Ability生命周期

20220116125626

onStart()

·当系统首次创建Paqe实例时,触发该回调。对于一个Page实例,该回调在其生命周期过程中仅触发一次,Page在该逻辑后将进入INACTIVE状态。开发者必须重写该方法,并在此配置默认展示的AbilitySlice。

@Override
public void onStart(Intent intent){super.onStart(intent);
super.setMainRoute(FooSlice.class.getName());}

onActive()

onlnactive&onBackground

onForeground()

onStop()

2.5 AbilitySlice生命周期

实例化

@Override
protected void onStart(Intent intent){
    super.onStart(intent);
	setUlContent(ResourceTable.Layout_main_layout);
}

生命周期关联

生命周期变化

AbilitySlice实例栈

20220116133924

AbilitySlice间导航

同一Page内导航

·当发起导航的AbilitySlice和导航目标的AbilitySlice处于同一个Page时,您可以通过present()方法实现导航。

@Override
protected void onStart(Intent intent){
    Button button = ...;
    button.setClickedListener(listener -> present(new TargetSlice(), newlntent()));
}

AbilitySlice间数据传递

源AbilitySlice

@Override
protected void onStart(Intent intent){
    ..
    Button button = ..;
    button.setClickedListener(listener -> presentForResult(new TargetSlice(), new Intent(),0));
    ..
}
    
@Override
protected void onResult(int requestCode,Intent resultlntent) {
    if (requestCode == 0) {
    //Process resultlntent here.
    }
}

不同Page间导航

3.Service Ability

3.1 创建Service

onConnect()

onDisconnect&onStop

public class ServiceAbility extends Ability {
    @Override
    public void onStart(lntent intent){
        super.onStart(intent);
    }
    @Override
    public void onCommand(Intent intent, boolean restart, intstartld) {
        super.onCommand(intent, restart, startld);
    }
    @Override
    public lRemoteObject onConnect(Intent intent){
        super.onConnect(intent);
        return null;
    }
}
@Override
public void onDisconnect(Intentintent) {
	super.onDisconnect(intent);
}
@Override
public void onStop() {
	super.onStop();
}

3.2 注册Service

Service也需要在应用配置文件中进行注册,注册类型type需要设置为service

{
    "module": {
        "abilities": [
            {
                "name": ".ServiceAbility",
                "type": "service",
                "visible": true
            }
        ]
    }
}

3.3 启动Service

本地Service启动

Intent intent = new Intent();

Operation operation = new Intent.OperationBuilder().withDeviceld("").withBundleName("com.huawei.hiworld.himusic").withAbilityName("com.huawei.hiworld.himusic.ServiceAbility").build();

intent.setOperation(operation);
startAbility(intent);

远程设备Service启动

Operation operation = new Intent.OperationBuilder()
.withDeviceld("deviceld")
.withBundleName("com.huawei.hiworld.himusic")
.withAbilityName("com.huawei.hiworld.himusic.ServiceAbility")//设置支持分布式调度系统多设备启动的标识
.withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE).build();

Intent intent = new Intent();
intent.setOperation(operation);
startAbility(intent);

startAbility的两种场景
执行上述代码后,Ability将通过startAbility()方法来启动Service

3.4 连接Service

3.5 生命周期

Service回调函数

20220116173535

前台Service

//创建通知,其中1005为notificationld
NotificationRequest request = new NotificationRequest(1005);
NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
content.setTitle("title").setText("text");
NotificationRequest.NotificationContent notificationContent = new  NotificationRequest.NotificationContent(content);
request.setContent(notificationContent);
//绑定通知,1005为创建通知时传入的notificationldkeepBackgroundRunning(1005, request);

{
    "name": ".ServiceAbility",
    "type": "service",
    "visible": true,
    "backgroundModes":["dataTransfer" ,"location"]
}

4.Intent

内部结构

20220116203341

lntent的分类

显式lntent的使用

Intent intent = new Intent();
/通过Intent中的OperationBuilder类构造operation对象,指定设备标识(空串表示当前设备)、应用包名、Ability名称
Operation operation = new lntent.OperationBuilder()
.withDeviceId("")
.withBundleName("com.demoapp")
.withAbilityName("com.demoapp.FooAbility").build();
//把operation设置到intent中intent.setOperation(operation);startAbility(intent);

使用Intent进行数据传递

数据传输示例
·设FA1和FA2之间的Intent名为secondIntent,则数据传输代码如下:

隐式lntent的使用

请求方

private void queryWeather() {
    lntent intent = new Intent();
    Operation operation = new Intent.OperationBuilder().withAction(Intent.ACTION_QUERY_WEATHER).build();
    intent.setOperation(operation);
    startAbilityForResult(intent, REQ_CODE_QUERY_WEATHER)
}

@Override
protected void onAbilityResult(int requestCode, int resultCode, Intent resultData){
    switch (requestCode){
        case REQ_CODE_QUERY_WEATHER:  //Do something with result.
            ...
            return;
        default:
            ...
    }
}

处理方

{
    "module": {
        "abilities": [
            {
                "skills":[
                    {
                        "actions":["ability.intent.QUERY_WEATHER"]
                    }
                ]
            }
        ]
    }
}
@Override
protected void onStart(Intent intent){
    addActionRoute(Intent.ACTION_QUERY_WEATHER, DemoSlice.class.getName());
}
Override
protected void onActive() {
    Intent resultIntent = new Intent();setResult(0, resultIntent);
}

5.访问后台服务获取电池电量Demo

1.建立前台FA显示电量信息:

​ 前台FA有两个可视化元素,一个Text,用来显示获得的手机电量,一个Button,用来触发调用后台服务事件。

<Text
ohos:id="$+id:text_helloworld"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_ability_main"
ohos:layout_alignment="horizontal_center"
ohos:text="$string:mainability_HelloWorld"
ohos:text_size="20vp"
>

前端搭建

<Button
ohos:id="$+id:button_battery"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_ability_main"
ohos:layout_alignment="horizontal_center"
ohos:text="BatteryInfo"
ohos:text_size="30vp"
>

2.连接后台服务:

​ 调用connectAbility(intent,connection)连接后台服务,其中Intent的operation参数已经指明服务所在设备id,包名和包含的能力名称,参数connection为AbilityConnection类型。

private void startBatteryService() {
    Operation operation = new Intent.OperationBuilder().withDeviceld("")
    .withBundleName("com.whu.batteryjavacallpa")
    .withAbilityName("com.whu.batteryjavacallpa.Batterylnfo").build();
    Intent intent = new Intent();
    intent.setOperation(operation);
    connectAbility(intent, connection);
}

3.建立后台服务BatteryInfo

新建Service Ability,该服务没有界面,纯粹提供电量读取服务功能。该服务中除了基本的电量获取函数getBatteryInfo,最重要是完成Service Ability的重载函数onConnect(Intent intent)。意味着当前台FA连接后台服务时会触发onConnect事件,在该事件中获取电量。

private String getBatteryInfo() {
    StringBuilder stringBuilder = new StringBuilder();
    boolean isCharging = getChargingStatus();
    double batteryValue = getBatteryLevel();
    stringBuilder
    .append("电量还剩")
    .append(batteryValue+"% ,"+ System.lineSeparator)).append("正在充电: "")
    .append(isCharging);
}
	return stringBuilder.toString();
}

lRemoteObject接口

@Override
public IRemoteObject onConnect(Intent intent){
    MyRemote thisRemote = new MyRemote();
    thisRemote.butery = getBatterylnfo();
	return thisRemote;
}

4.建立IRemoteObject子类MyRemote的实例

​ ,并返回给onConnect函数∶新建MyRemote类,MyRemote类为LocalRemoteObject的子类,而LocalRemoteObject为RemoteObject的子类。返回的MyRemote的实例会返回到客户端

public class MyRemote extends LocalRemoteObject {
    public String butery = "";//添加变量获取电量返回值
    public MyRemote() {
		super();
	}
}

5.前台FA调用后台服务函数

​ ,显示电量:客户端重载IAbilityConnection类的函数onAbilityConnectDone(ElementName elementName,lRemoteObject iRemoteObject,int resultCode),该函数在客户端与服务器连接建立好后会触发,服务端返回
lRemoteObject对象。解析该对象,得到手机电量。

private lAbilityConnection connection = new IAbilityConnection() {
    @Override
    public void onAbilityConnectDone(ElementName elementName, IKemoteubject likeolevu]eul, mresultCode){
        HiLog.info(LABEL_LOG, "%{public]s" , "onAbilityConnectDone resultCode : " + resultCode);
        	MyRemote clientRemote = (MyRemote) iRemoteObject;
        	Text txt = (Text)findComponentByld(ResourceTable.ld_text_helloworld);
        	txt.setText(clientRemote.butery);
       		Button btn = (Button)findComponentByld(ResourceTable.ld_button_battery);
        btn.setText("电池状态");
    }
}

20220116204352

private lAbilityConnection connection = new IAbilityConnection() {
    @Override
    public void onAbilityConnectDone(ElementName elementName, IKemoteubject likeolevu]eul, mresultCode){
        HiLog.info(LABEL_LOG, "%{public]s" , "onAbilityConnectDone resultCode : " + resultCode);
        	MyRemote clientRemote = (MyRemote) iRemoteObject;
        	Text txt = (Text)findComponentByld(ResourceTable.ld_text_helloworld);
        	txt.setText(clientRemote.butery);
       		Button btn = (Button)findComponentByld(ResourceTable.ld_button_battery);
        btn.setText("电池状态");
    }
}

[外链图片转存中…(img-OtjTEBCm-1642394987751)]

标签:Ability,Service,armonyOS,核心,AbilitySlice,CH4,Intent,intent,Page
来源: https://blog.csdn.net/weixin_46227276/article/details/122537548