HarmonyOS实战—初识服务卡片
Posted 笔触狂放
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HarmonyOS实战—初识服务卡片相关的知识,希望对你有一定的参考价值。
[本文正在参与“有奖征文| HarmonyOS征文大赛”活动]
目录
服务卡片概述
服务卡片(以下简称“卡片”)是FA的一种界面展示形式,将FA的重要信息或操作前置到卡片,以达到服务直达,减少体验层级的目的。
卡片常用于嵌入到其他应用(当前只支持系统应用)中作为其界面的一部分显示,并支持拉起页面,发送消息等基础的交互功能。卡片使用方负责显示卡片。
FA示例如下图所示。
基本概念
- 卡片提供方
提供卡片显示内容的HarmonyOS应用或原子化服务,控制卡片的显示内容、控件布局以及控件点击事件。
- 卡片使用方
显示卡片内容的宿主应用,控制卡片在宿主中展示的位置。
- 卡片管理服务
用于管理系统中所添加卡片的常驻代理服务,包括卡片对象的管理与使用,以及卡片周期性刷新等。
运作机制
卡片管理服务包含以下模块:
- 周期性刷新:在卡片添加后,根据卡片的刷新策略启动定时任务周期性触发卡片的刷新。
- 卡片缓存管理:在卡片添加到卡片管理服务后,对卡片的视图信息进行缓存,以便下次获取卡片时可以直接返回缓存数据,降低时延。
- 卡片生命周期管理:对于卡片切换到后台或者被遮挡时,暂停卡片的刷新;以及卡片的升级/卸载场景下对卡片数据的更新和清理。
- 卡片使用方对象管理:对卡片使用方的RPC对象进行管理,用于使用方请求进行校验以及对卡片更新后的回调处理。
- 通信适配层:负责与卡片使用方和提供方进行RPC通信。
卡片提供方包含以下模块:
- 卡片服务:由卡片提供方开发者实现,开发者实现onCreateForm、onUpdateForm和onDeleteForm处理创建卡片、更新卡片以及删除卡片等请求,提供相应的卡片服务。
- 卡片提供方实例管理模块:由卡片提供方开发者实现,负责对卡片管理服务分配的卡片实例进行持久化管理。
- 通信适配层:由HarmonyOS SDK提供,负责与卡片管理服务通信,用于将卡片的更新数据主动推送到卡片管理服务。
1.基础步骤
- 打开DevEco Studio软件,新建项目
- 创建手机应用,使用java编程语言
- 填写项目信息
- 展示项目目录列表
2.创建服务卡片
- 鸿蒙系统开发提供了很多卡片样式供开发者选择
- 这里选择网格卡片样式
- 填写设置卡片信息
- 这里我选择了2*2和2*4的卡片,卡片创建完成后,在config.json项目配置文件中会发到卡片的配置信息
- 在layout文件夹下可以看到系统自动创建的所选择的卡片布局文件,开发者可以直接在该布局上设计自己的卡片效果
3. 2*2的音乐卡片设计
- 其对应的布局代码如下
<?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="#66000000"
ohos:orientation="vertical"
ohos:remote="true">
<DirectionalLayout
ohos:height="match_content"
ohos:width="match_parent"
ohos:alignment="vertical_center"
ohos:orientation="horizontal"
ohos:weight="1">
<Image
ohos:height="60vp"
ohos:width="60vp"
ohos:image_src="$media:campuslife_bg"
ohos:scale_mode="zoom_start"
ohos:start_margin="12vp"
ohos:top_margin="12vp"/>
<DirectionalLayout
ohos:height="60vp"
ohos:margin="5fp"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="vertical">
<Text
ohos:height="match_content"
ohos:width="match_parent"
ohos:text="歌名"
ohos:text_color="#E5FFFFFF"
ohos:text_size="19fp"
ohos:text_weight="900"
ohos:truncation_mode="ellipsis_at_end"/>
<Text
ohos:height="match_content"
ohos:width="match_parent"
ohos:text="歌手名称"
ohos:text_color="#aaFFFFFF"
ohos:text_size="15fp"
ohos:text_weight="600"
ohos:top_margin="2vp"
ohos:truncation_mode="ellipsis_at_end"/>
</DirectionalLayout>
</DirectionalLayout>
<DirectionalLayout
ohos:height="match_content"
ohos:width="match_parent"
ohos:alignment="bottom"
ohos:margin="12vp"
ohos:orientation="horizontal"
ohos:weight="1">
<Image
ohos:height="30vp"
ohos:width="30vp"
ohos:image_src="$media:button_playmode_shuffle"
ohos:scale_mode="stretch"
ohos:weight="1"/>
<Image
ohos:height="30vp"
ohos:width="30vp"
ohos:image_src="$media:button_previous"
ohos:scale_mode="stretch"
ohos:weight="1"/>
<Image
ohos:height="30vp"
ohos:width="30vp"
ohos:image_src="$media:button_play"
ohos:scale_mode="stretch"
ohos:weight="1"/>
<Image
ohos:height="30vp"
ohos:width="30vp"
ohos:image_src="$media:button_next"
ohos:scale_mode="stretch"
ohos:weight="1"/>
<Image
ohos:height="30vp"
ohos:width="30vp"
ohos:image_src="$media:button_favorite"
ohos:scale_mode="stretch"
ohos:weight="1"/>
</DirectionalLayout>
</DirectionalLayout>
4. 2*4的运动出行卡片
- 其2*4卡片的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="#aaffffff"
ohos:margin="10fp"
ohos:orientation="vertical"
ohos:remote="true">
<DirectionalLayout
ohos:height="match_content"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="horizontal"
ohos:weight="1">
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_facard_text"
ohos:text="美食"
ohos:padding="5fp"
ohos:margin="8fp"
ohos:text_alignment="center"
ohos:text_size="12fp"
ohos:weight="1"/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_facard_text"
ohos:padding="5fp"
ohos:margin="8fp"
ohos:text="酒店"
ohos:text_alignment="center"
ohos:text_size="12fp"
ohos:weight="1"/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_facard_text"
ohos:text="景点"
ohos:padding="5fp"
ohos:margin="8fp"
ohos:text_alignment="center"
ohos:text_size="12fp"
ohos:weight="1"/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_facard_text"
ohos:text="加油站"
ohos:padding="5fp"
ohos:margin="8fp"
ohos:text_alignment="center"
ohos:text_size="12fp"
ohos:weight="1"/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_facard_text"
ohos:text="超市"
ohos:padding="5fp"
ohos:margin="8fp"
ohos:text_alignment="center"
ohos:text_size="12fp"
ohos:weight="1"/>
</DirectionalLayout>
<DirectionalLayout
ohos:height="match_content"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="horizontal"
ohos:weight="1">
<DirectionalLayout
ohos:height="match_parent"
ohos:width="match_content"
ohos:alignment="center"
ohos:orientation="vertical"
ohos:weight="1">
<Image
ohos:height="40vp"
ohos:width="40vp"
ohos:image_src="$media:ic_sport_hauxue2"/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:text="滑雪"
ohos:text_size="14fp"/>
</DirectionalLayout>
<DirectionalLayout
ohos:height="match_parent"
ohos:width="match_content"
ohos:alignment="center"
ohos:orientation="vertical"
ohos:weight="1">
<Image
ohos:height="40vp"
ohos:width="40vp"
ohos:image_src="$media:ic_sport_jianshen2"/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:text="健身"
ohos:text_size="14fp"/>
</DirectionalLayout>
<DirectionalLayout
ohos:height="match_parent"
ohos:width="match_content"
ohos:alignment="center"
ohos:orientation="vertical"
ohos:weight="1">
<Image
ohos:height="40vp"
ohos:width="40vp"
ohos:image_src="$media:ic_sport_panyan2"/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:text="攀岩"
ohos:text_size="14fp"/>
</DirectionalLayout>
<DirectionalLayout
ohos:height="match_parent"
ohos:width="match_content"
ohos:alignment="center"
ohos:orientation="vertical"
ohos:weight="1">
<Image
ohos:height="40vp"
ohos:width="40vp"
ohos:image_src="$media:ic_sport_youyong2"/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:text="游泳"
ohos:text_size="14fp"/>
</DirectionalLayout>
<DirectionalLayout
ohos:height="match_parent"
ohos:width="match_content"
ohos:alignment="center"
ohos:orientation="vertical"
ohos:weight="1">
<Image
ohos:height="40vp"
ohos:width="40vp"
ohos:image_src="$media:ic_sport_yujia2"/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:text="瑜伽"
ohos:text_size="14fp"/>
</DirectionalLayout>
</DirectionalLayout>
</DirectionalLayout>
5.修改应用启动卡片代码
我们有点鸿蒙基础的知道,项目的启动需要指定MainAbility界面,我们需要修改MainAbility界面,指定其默认展示的卡片,以及加载我们设计的多个服务卡片
其MainAbility代码如下
package com.example.facardproject2;
import com.example.facardproject2.slice.MainAbilitySlice;
import com.example.facardproject2.widget.FormController;
import com.example.facardproject2.widget.FormControllerManager;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
public class MainAbility extends Ability {
public static final int DEFAULT_DIMENSION_2X4 = 2;
public static final int DIMENSION_2X2 = 1;
public static final int DIMENSION_4X4 = 3;
//public static final int DIMENSION_4X4 = 4;
private static final int INVALID_FORM_ID = -1;
private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, MainAbility.class.getName());
private String topWidgetSlice;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setMainRoute(MainAbilitySlice.class.getName());
if (intentFromWidget(intent)) {
topWidgetSlice = getRoutePageSlice(intent);
if (topWidgetSlice != null) {
setMainRoute(topWidgetSlice);
}
}
stopAbility(intent);
}
//创建卡片信息并返回卡片内容
@Override
protected ProviderFormInfo onCreateForm(Intent intent) {
HiLog.info(TAG, "onCreateForm");
long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
String formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
int dimension = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, DEFAULT_DIMENSION_2X4);
HiLog.info(TAG, "onCreateForm: formId=" + formId + ",formName=" + formName);
FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
FormController formController = formControllerManager.getController(formId);
//通过调用布局Id将卡片布局与卡片信息进行绑定
formController = (formController == null) ? formControllerManager.createFormController(formId,
formName, dimension) : formController;
if (formController == null) {
HiLog.error(TAG, "Get null controller. formId: " + formId + ", formName: " + formName);
return null;
}
return formController.bindFormData();
}
//更新卡片信息
@Override
protected void onUpdateForm(long formId) {
HiLog.info(TAG, "onUpdateForm");
super.onUpdateForm(formId);
FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
FormController formController = formControllerManager.getController(formId);
formController.updateFormData(formId);
}
//删除卡片
@Override
protected void onDeleteForm(long formId) {
HiLog.info(TAG, "onDeleteForm: formId=" + formId);
super.onDeleteForm(formId);
FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
formControllerManager.deleteFormController(formId);
}
//卡片手势触发
@Override
protected void onTriggerFormEvent(long formId, String message) {
HiLog.info(TAG, "onTriggerFormEvent: " + message);
super.onTriggerFormEvent(formId, message);
FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
FormController formController = formControllerManager.getController(formId);
formController.onTriggerFormEvent(formId, message);
}
@Override
public void onNewIntent(Intent intent) {
if (intentFromWidget(intent)) { // Only response to it when starting from a service widget.
String newWidgetSlice = getRoutePageSlice(intent);
if (topWidgetSlice == null || !topWidgetSlice.equals(newWidgetSlice)) {
topWidgetSlice = newWidgetSlice;
restart();
}
}
}
private boolean intentFromWidget(Intent intent) {
long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
return formId != INVALID_FORM_ID;
}
//跳转至对应的卡片界面
private String getRoutePageSlice(Intent intent) {
long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
if (formId == INVALID_FORM_ID) {
return null;
}
FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
FormController formController = formControllerManager.getController(formId);
if (formController == null) {
return null;
}
Class<? extends AbilitySlice> clazz = formController.getRoutePageSlice(intent);
if (clazz == null) {
return null;
}
return clazz.getName();
}
}
6.创建服务卡片控制代码
在项目的包中,新建widget包名,并创建服务卡片控制管理器类,服务卡片控制抽象类以及服务卡片实现类
创建卡片控制器,用于创建卡片,加载卡片,更新卡片和删除卡片
package com.example.facardproject2.widget;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
public abstract class FormController {
protected final Context context;
protected final String formName;
protected final int dimension;
public FormController(Context context, String formName, Integer dimension) {
this.context = context;
this.formName = formName;
this.dimension = dimension;
}
/**
* 创建卡片信息提供者
*/
public abstract ProviderFormInfo bindFormData();
/**
* 更新卡片信息
*/
public abstract void updateFormData(long formId, Object... vars);
/**
* 在接收服务小部件消息事件时调用
*/
public abstract void onTriggerFormEvent(long formId, String message);
/**
* 获取路由的目标界面
*/
public abstract Class<? extends AbilitySlice> getRoutePageSlice(Intent intent);
}
创建卡片实现类,用于根据实际创建的卡片样式加载卡片对象
package com.example.facardproject2.widget;
import com.example.facardproject2.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import java.util.HashMap;
import java.util.Map;
public class CardWidgetImpl extends FormController {
public static final int DIMENSION_2X2 = 1;
public static final int DIMENSION_4X4 = 3;
private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, CardWidgetImpl.class.getName());
private static final int DEFAULT_DIMENSION_2X4 = 2;
private static final Map<Integer, Integer> RESOURCE_ID_MAP = new HashMap<>();
static {
RESOURCE_ID_MAP.put(DIMENSION_2X2, ResourceTable.Layout_form_grid_pattern_service_widget1_2_2);
RESOURCE_ID_MAP.put(DEFAULT_DIMENSION_2X4, ResourceTable.Layout_form_grid_pattern_service_widget1_2_4);
RESOURCE_ID_MAP.put(DIMENSION_4X4, ResourceTable.Layout_form_grid_pattern_service_widget1_4_4);
}
public CardWidgetImpl(Context context, String formName, Integer dimension) {
super(context, formName, dimension);
}
//创建好卡片服务后,在界面展示卡片
@Override
public ProviderFormInfo bindFormData() {
HiLog.info(TAG, "bind form data when create form");
return new ProviderFormInfo(RESOURCE_ID_MAP.get(dimension), context);
}
//更新卡片信息
@Override
public void updateFormData(long formId, Object... vars) {
HiLog.info(TAG, "update form data timing, default 30 minutes");
}
//卡片中内容手势触发方法
@Override
public void onTriggerFormEvent(long formId, String message) {
HiLog.info(TAG, "handle card click event.");
}
@Override
public Class<? extends AbilitySlice> getRoutePageSlice(Intent intent) {
HiLog.info(TAG, "get the default page to route when you click card.");
return null;
}
}
创建卡片控制管理器类,用于调用用户选择的卡片显示效果,以及触发组件事件
package com.example.facardproject2.widget;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class FormControllerManager {
private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, FormControllerManager.class.getName());
private static final String PACKAGE_PATH = "com.example.carddemo.widget";
private static final String SHARED_SP_NAME = "form_info_sp.xml";
private static final String FORM_NAME = "formName";
private static final String DIMENSION = "dimension";
private static FormControllerManager managerInstance = null;
private final HashMap<Long, com.example.facardproject2.widget.FormController> controllerHashMap = new HashMap<>();
private final Context context;
private final Preferences preferences;
/**
* 初始化构造器
*
* @param context instance of Context.
*/
private FormControllerManager(Context context) {
this.context = context;
DatabaseHelper databaseHelper = new DatabaseHelper(this.context.getApplicationContext());
preferences = databaseHelper.getPreferences(SHARED_SP_NAME);
}
/**
* FormControllerManager 实例化
*
* @param context instance of Context.
* @return FormControllerManager instance.
*/
public static FormControllerManager getInstance(Context context) {
if (managerInstance == null) {
synchronized (FormControllerManager.class) {
if (managerInstance == null) {
managerInstance = new FormControllerManager(context);
}
}
}
return managerInstance;
}
/**
* 通过构造器将传入的卡片信息进行封装,返回卡片服务
*
* @param formId form id.
* @param formName form name.
* @param dimension form dimension
* @return FormController form controller
*/
public FormController createFormController(long formId, String formName, int dimension) {
synchronized (controllerHashMap) {
if (formId < 0 || formName.isEmpty()) {
return null;
}
HiLog.info(TAG,
"saveFormId() formId: " + formId + ", formName: " + formName + ", preferences: " + preferences);
if (preferences != null) {
ZSONObject formObj = new ZSONObject();
formObj.put(FORM_NAME, formName);
formObj.put(DIMENSION, dimension);
preferences.putString(Long.toString(formId), ZSONObject.toZSONString(formObj));
preferences.flushSync();
}
// Create controller instance.
FormController controller = newInstance(formName, dimension, context);
// Cache the controller.
if (controller != null) {
if (!controllerHashMap.containsKey(formId)) {
controllerHashMap.put(formId, controller);
}
}
return controller;
}
}
/**
* 获取卡片控制器实例
*
* @param formId form id.
* @return the instance of form controller.
*/
public FormController getController(long formId) {
synchronized (controllerHashMap) {
if (controllerHashMap.containsKey(formId)) {
return controllerHashMap.get(formId);
}
Map<String, ?> forms = preferences.getAll();
String formIdString = Long.toString(formId);
if (forms.containsKey(formIdString)) {
ZSONObject formObj = ZSONObject.stringToZSON((String) forms.get(formIdString));
String formName = formObj.getString(FORM_NAME);
int dimension = formObj.getIntValue(DIMENSION);
FormController controller = newInstance(formName, dimension, context);
controllerHashMap.put(formId, controller);
}
return controllerHashMap.get(formId);
}
}
private FormController newInstance(String formName, int dimension, Context context) {
FormController ctrInstance = null;
if (formName == null || formName.isEmpty()) {
HiLog.error(TAG, "newInstance() get empty form name");
return ctrInstance;
}
try {
String className = PACKAGE_PATH + "." + formName.toLowerCase(Locale.ROOT) + "."
+ getClassNameByFormName(formName);
Class<?> clazz = Class.forName(className);
if (clazz != null) {
Object controllerInstance = clazz.getConstructor(Context.class, String.class, Integer.class)
.newInstance(context, formName, dimension);
if (controllerInstance instanceof FormController) {
ctrInstance = (FormController) controllerInstance;
}
}
} catch (NoSuchMethodException | InstantiationException | IllegalArgumentException | InvocationTargetException
| IllegalAccessException | ClassNotFoundException | SecurityException exception) {
HiLog.error(TAG, "newInstance() get exception: " + exception.getMessage());
}
return ctrInstance;
}
/**
* 从数组中获取所有卡片id
*
* @return form id list
*/
public List<Long> getAllFormIdFromSharePreference() {
List<Long> result = new ArrayList<>();
Map<String, ?> forms = preferences.getAll();
for (String formId : forms.keySet()) {
result.add(Long.parseLong(formId));
}
return result;
}
/**
* 删除卡片服务
*
* @param formId form id
*/
public void deleteFormController(long formId) {
synchronized (controllerHashMap) {
preferences.delete(Long.toString(formId));
preferences.flushSync();
controllerHashMap.remove(formId);
}
}
private String getClassNameByFormName(String formName) {
String[] strings = formName.split("_");
StringBuilder result = new StringBuilder();
for (String string : strings) {
result.append(string);
}
char[] charResult = result.toString().toCharArray();
charResult[0] = (charResult[0] >= 'a' && charResult[0] <= 'z') ? (char) (charResult[0] - 32) : charResult[0];
return String.copyValueOf(charResult) + "Impl";
}
}
7.运行步骤
选择Tools->HVD Manager开启华为模拟器
弹出登录华为账号控制台
跳转网站,进入华为官网,登录华为账号
登录成功后,DevEco Studio会展示可以使用的不同设备的远程模拟器
这里我选择P40模拟器
8.运行效果
运行后,模拟器上会发现多了一个应用
长按应用图标,弹出“服务卡片”选项
在服务卡片中,你能找到“音乐卡片”和“运动出行卡片”
可以将喜欢的卡片设置为默认卡片,设置为默认的卡片,可以在点击应用图标上滑显示
点击右上角可以将该卡片添加在桌面上,作为进入应用的快捷方式
本文到这里就结束了,希望对大家学习服务卡片功能提供帮助。
需要代码案例的请在这里下载
以上是关于HarmonyOS实战—初识服务卡片的主要内容,如果未能解决你的问题,请参考以下文章