[本文正在參與“有獎征文| 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征文大賽”活動]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/292095.html
標籤:其他
上一篇:嵌入式Linux入門---第一篇
