介紹
服務卡片指導文檔位于“ 開發(fā)/應用模型/Stage模型開發(fā)指導/Stage模型應用組件 ”路徑下,說明其極其重要。
本篇文章將分享實現服務卡片的過程和代碼
準備
- 請參照[官方指導],創(chuàng)建一個Demo工程,選擇Stage模型
 
實踐總結
- 應用打包時,不能選擇“Deploy Muti Hap Packages”方式, 否則服務卡片不會顯示任何內容
 - 官方指導中沒有提示添加權限“ohos.permission.KEEP_BACKGROUND_RUNNING”,如果不添加,則無法使用call方式來刷新卡片數據
 - 卡片首次創(chuàng)建時,卡片Id無法傳入到卡片中,需通過延時機制,二次更新
 
效果

卡片元素說明
- 卡片共有使用到了7個控件
 - 5個Text, 1個Image, 1個Rect
 - Text('call') : 可點擊,實驗call事件刷新卡片內容
 - Text('router'): 可點擊,實驗router事件刷新卡片內容
 - Text('message'): 可點擊,實驗message事件刷新卡片內容
 - Rect(): 實驗卡片動畫效果
 
服務卡片教程
- 請完全按照“創(chuàng)建一個ArkTS卡片”
 - 修改生成的卡片代碼(WidgetCard.ets)
 
let storageCard = new LocalStorage()
@Entry(storageCard)
@Component
struct WidgetCard {
  /*
   * The mini title.
   */
  readonly MINI_TITLE: string = 'Title';
  /*
   * The item title.
   */
  @LocalStorageProp('ITEM_TITLE')ITEM_TITLE: string = '標題';
  /*
   * The item content.
   */
  @LocalStorageProp('ITEM_CONTENT') ITEM_CONTENT: string = '天氣不錯';
  /*
   * The action type.
   */
  readonly ACTION_TYPE: string = 'router';
  /*
   * The ability name.
  */
  readonly ABILITY_NAME: string = 'EntryAbility';
  /*
   * The message.
   */
  readonly MESSAGE: string = '來自服務卡片';
  /*
   * The mini display priority.
   */
  readonly MINI_DISPLAY_PRIORITY: number = 2;
  /*
   * The max line.
   */
  readonly MAX_LINES: number = 1;
  /*
   * The with percentage setting.
   */
  readonly FULL_WIDTH_PERCENT: string = '100%';
  /*
   * The height percentage setting.
   */
  readonly FULL_HEIGHT_PERCENT: string = '100%';
  /*
   * Image height percentage setting.
   */
  readonly IMAGE_HEIGHT_PERCENT: string = '64%';
  @State mini: boolean = false;
  @State rectWidth: string = '30%'
  @LocalStorageProp('formId') formId: string = '0';
  build() {
    Row() {
      Column() {
        if (this.mini) {
          Column() {
            Text(this.MINI_TITLE)
              .fontSize($r('app.float.mini_title_font_size'))
              .fontColor($r('app.color.mini_text_font_color'))
              .margin({
                left: $r('app.float.mini_title_margin'),
                bottom: $r('app.float.mini_title_margin')
              })
          }
          .width(this.FULL_WIDTH_PERCENT)
          .alignItems(HorizontalAlign.End)
          .backgroundImageSize(ImageSize.Cover)
          .backgroundImage($r("app.media.ic_widget"), ImageRepeat.NoRepeat)
          .displayPriority(this.MINI_DISPLAY_PRIORITY)
        }
        Stack(){
          Image($r("app.media.ic_widget"))
            .width(this.FULL_WIDTH_PERCENT)
            .height('100%')
            .objectFit(ImageFit.Cover)
            .borderRadius($r('app.float.image_border_radius'))
          Rect()
            .width(this.rectWidth)
            .height('100%')
            .fill('#60ff0000')
            .animation({
              duration: 3000,
              curve: Curve.Linear,
              playMode: PlayMode.Normal,
              iterations: -1,
              onFinish:()= >{
                  if(this.rectWidth == '30%'){
                    this.rectWidth = '50%'
                  } else {
                    this.rectWidth = '30%'
                  }
              }})
          Row(){
            Column({space: 20}){
              Text('call')
                .fontColor(Color.Red)
                .onClick(()= >{
                  console.log('formId: '+this.formId)
                  postCardAction(this, {
                    'action': 'call',
                    'abilityName': 'EntryAbility',
                    'params': {
                      'method': 'funA',
                      'formId': this.formId
                    }
                  });
                })
              Text('router')
                .onClick(()= >{
                  postCardAction(this, {
                    'action': 'router',
                    'abilityName': 'EntryAbility',
                    'params': {
                      'msgTest': 'messageEvent'
                    }
                  });
                })
            }
            Column(){
              Text('message')
                .fontColor(Color.Green)
                .onClick(()= >{
                  postCardAction(this, {
                    'action': 'message',
                    'params': {
                      'msgTest': 'messageEvent'
                    }
                  });
                })
            }
          }.height('100%')
        }
        .width(this.FULL_WIDTH_PERCENT)
        .height(this.IMAGE_HEIGHT_PERCENT)
        Blank()
        Text(this.ITEM_TITLE)
          .fontSize($r('app.float.normal_title_font_size'))
        Text(this.ITEM_CONTENT)
          .maxLines(this.MAX_LINES)
          .fontSize($r('app.float.normal_content_font_size'))
          .textOverflow({ overflow: TextOverflow.Ellipsis })
      }
      .width(this.FULL_WIDTH_PERCENT)
      .height(this.FULL_HEIGHT_PERCENT)
      .alignItems(HorizontalAlign.Start)
      .backgroundColor($r('app.color.start_window_background'))
    }
    .height(this.FULL_HEIGHT_PERCENT)
    .alignItems(VerticalAlign.Top)
    .padding($r('app.float.row_padding'))
    .onClick(() = > {
      postCardAction(this, {
        "action": this.ACTION_TYPE,
        "abilityName": this.ABILITY_NAME,
        "params": {
          "message": this.MESSAGE
        }
      });
    })
  }
}
- 修改應用入口EntryAbility.ets
 
import window from '@ohos.window';
import UIAbility from '@ohos.app.ability.UIAbility';
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
import formInfo from '@ohos.app.form.formInfo';
export default class EntryAbility extends UIAbility {
  storage: LocalStorage
  onCreate(want, launchParam) {
    try{
      let params = JSON.parse(want.parameters.params);
      console.log('onCreate ' + params['message'])
      this.storage = new LocalStorage({'ext': params['message']})
    } catch (e){
      console.log(e)
    }
    try{
      // 監(jiān)聽call事件所需的方法
      this.callee.on('funA', FunACall);
    } catch (e){
      console.log(e)
    }
    if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
      let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY];
      updateCardContent(curFormId, "EntryAbility", "router-welcome")
    }
  }
  onNewWant(want, launchParam) {
    try{
      let params = JSON.parse(want.parameters.params);
      console.log('onNewWant ' + params['message'])
      this.storage = new LocalStorage({'ext': params['message']})
    } catch (e){
       console.log(e)
    }
  }
  onWindowStageCreate(windowStage: window.WindowStage) {
    windowStage.loadContent('pages/Index', this.storage, (err, data) = > {
     });
  }
  onDestroy(){
    console.log('onDestroy')
    // this.callee.off('funA')
  }
}
// 在收到call事件后會觸發(fā)callee監(jiān)聽的方法
function FunACall(data) {
  // 獲取call事件中傳遞的所有參數
  try{
    let params = JSON.parse(data.readString())
    if (params.formId !== undefined) {
      let curFormId = params.formId;
      updateCardContent(curFormId, "EntryAbility", "caller-welcome")
    }
  } catch (e){
    console.log(e)
  }
  return null;
}
function updateCardContent(formId, method, content){
  let formData = {
    'ITEM_TITLE': method, // 和卡片布局中對應
    'ITEM_CONTENT': content, // 和卡片布局中對應
  };
  let formInfo = formBindingData.createFormBindingData(formData)
  formProvider.updateForm(formId, formInfo).then((data) = > {
    console.info('FormAbility updateForm success.' + JSON.stringify(data));
  }).catch((error) = > {
    console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
  })
}
- 修改應用入入口頁面Index.ets
 
let storage = new LocalStorage()
@Entry(storage)
@Component
struct Page {
  @State message: string = 'Hello World'
  @LocalStorageProp('ext') extLocalStorageParms: string = '';
  aboutToAppear(){
    console.log(this.extLocalStorageParms)
    if(this.extLocalStorageParms){
      this.message = this.extLocalStorageParms
    }
  }
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}
- 修改EntryFormAbility.ets
 
import formInfo from '@ohos.app.form.formInfo';
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formProvider from '@ohos.app.form.formProvider';
export default class EntryFormAbility extends FormExtensionAbility {
  onAddForm(want) {
    // Called to return a FormBindingData object.
    let formId = want.parameters["ohos.extra.param.key.form_identity"];
    let formData: Record< string, string > = {
      'formId': formId
    };
    console.log('onAddForm '+formId)
    let data = formBindingData.createFormBindingData(formData);
    setTimeout(()= >{
      formProvider.updateForm(formId, data).then((data) = > {
        console.info('FormAbility updateForm success.' + JSON.stringify(data));
      }).catch((error) = > {
        console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
      })
    }, 1500)
    return data
  }
  onCastToNormalForm(formId) {
    // Called when the form provider is notified that a temporary form is successfully
    // converted to a normal form.
    console.log('onCastToNormalForm')
  }
  onUpdateForm(formId) {
    // Called to notify the form provider to update a specified form.
    console.log('onUpdateForm')
  }
  onChangeFormVisibility(newStatus) {
    // Called when the form provider receives form events from the system.
    console.log('onChangeFormVisibility')
  }
  onFormEvent(formId, message) {
    // Called when a specified message event defined by the form provider is triggered.
    console.log(message)
    this.updateCardContent(formId)
  }
  onRemoveForm(formId) {
    // Called to notify the form provider that a specified form has been destroyed.
    console.log('onRemoveForm')
  }
  onAcquireFormState(want) {
    // Called to return a {@link FormState} object.
    return formInfo.FormState.READY;
  }
  updateCardContent(formId){
    let formData = {
      'ITEM_TITLE': 'EntryFormAbility', // 和卡片布局中對應
      'ITEM_CONTENT': 'welcome', // 和卡片布局中對應
    };
    let formInfo = formBindingData.createFormBindingData(formData)
    formProvider.updateForm(formId, formInfo).then((data) = > {
      console.info('FormAbility updateForm success.' + JSON.stringify(data));
    }).catch((error) = > {
      console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
    })
  }
};
- 在module.json5中添加權限
 
"requestPermissions": [
      {
        "name":  "ohos.permission.KEEP_BACKGROUND_RUNNING",
        "usedScene": {
          "abilities": ["EntryAbility"],
          "when": "inuse"
        }
      }
    ]
- 最后一步,請確認你的打包方式沒有選擇“Deploy Multi Hap Packages”, 否則將無法看到服務卡片內容
 

審核編輯 黃宇
                        聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規(guī)問題,請聯(lián)系本站處理。
                        舉報投訴
                    
                    - 
                                鴻蒙
                                +關注
關注
60文章
2768瀏覽量
45192 - 
                                鴻蒙OS
                                +關注
關注
0文章
191瀏覽量
5283 
發(fā)布評論請先 登錄
相關推薦
                    熱點推薦
                  鴻蒙OS實戰(zhàn)開發(fā):【多設備自適應服務卡片】
服務卡片的布局和使用,其中卡片內容顯示使用了一次開發(fā),多端部署的能力實現多設備自適應。  
用到了卡片擴展模塊接口,[@ohos.app.
    
    
                    
    
一文看懂HarmonyOS服務卡片運行原理和開發(fā)方法
一、服務卡片概述1、什么是服務卡片HarmonyOS 2的到來,讓很多開發(fā)者眼前一亮。HarmonyOS 2推出的
    
                發(fā)表于 07-27 17:21        
                    
    
完整服務卡片項目開發(fā),為Bilibili添加服務卡片
已經被鴻蒙刷屏了。從安卓到鴻蒙,最直觀的變化應該就是服務卡片了。我也是在學習鴻蒙的同時,實際體驗一下服務
    
                發(fā)表于 09-03 20:49        
                    
    
鴻蒙OS 2.0手機版引起全國網友熱議 與安卓最大區(qū)別在哪里
網絡上曝光的鴻蒙OS 2.0手機開發(fā)者版本的真實界面顯示,鴻蒙OS 2.0
    
    
華為鴻蒙OS 2.0帶來哪些智慧體驗?
華為已經定于12月16日在北京發(fā)布鴻蒙OS 2.0手機開發(fā)者Beta版本。這不僅是手機鴻蒙OS的
    
    
鴻蒙OS 2.0手機開發(fā)者Beta版發(fā)布會在京舉辦
三個月前,鴻蒙OS 2.0正式在華為開發(fā)者大會2020亮相。12月16日,鴻蒙OS 2.0手機
    
    
鴻蒙OS2.0手機開發(fā)者Beta版登場
12 月 16 日,華為宣布正式推出鴻蒙 OS 的手機開發(fā)者 Beta 版,并正式面向個人/企業(yè)開發(fā)者公測鴻蒙 2.0,
    
    
如何在鴻蒙系統(tǒng)弄一個彩票查詢卡片
接觸鴻蒙開發(fā)已經有 3 個來月了,最近開始在看鴻蒙卡片開發(fā)。因為之前的開發(fā)大都是基于 Java 
    
    
一款鴻蒙版的嗶哩嗶哩服務卡片應用案例
介紹 這是一款純鴻蒙版的嗶哩嗶哩服務卡片應用。 6月2日鴻蒙發(fā)布,今年的六月已經被鴻蒙刷屏了。從安卓到鴻
    
                發(fā)表于 04-07 09:42        
                ?0次下載    
    
用Java開發(fā)HarmonyOS服務卡片
卡片服務:由卡片提供方開發(fā)者實現,開發(fā)者實現 onCreateForm、onUpdateForm 和 onDeleteForm 處理創(chuàng)建
    
    
效率大升!AI賦能鴻蒙萬能卡片開發(fā)
萬能卡片,作為鴻蒙生態(tài)應用和元服務的重要展示形式,憑借將關鍵信息和核心操作前置,實現服務直達、減少跳轉層級的體驗效果,備受用戶和開發(fā)者青睞。
    
    
                    
    
          
        
        
鴻蒙OS開發(fā)實例:【手擼服務卡片】
                
 
    
           
            
            
                
            
評論