精品国产人成在线_亚洲高清无码在线观看_国产在线视频国产永久2021_国产AV综合第一页一个的一区免费影院黑人_最近中文字幕MV高清在线视频

0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

鴻蒙OS開發案例:【Stage模型卡片】

jf_46214456 ? 來源:jf_46214456 ? 作者:jf_46214456 ? 2024-04-09 17:13 ? 次閱讀

Stage模型卡片

介紹

本示例展示了Stage模型卡片提供方的創建與使用。

用到了卡片擴展模塊接口,[@ohos.app.form.FormExtensionAbility] 。

卡片信息和狀態等相關類型和枚舉接口,[@ohos.app.form.formInfo] 。

卡片提供方相關接口的能力接口,[@ohos.app.form.formProvider] 。

應用組件間的信息傳遞接口,[@ohos.app.ability.Want]。

效果預覽

image.png

image.png

概念

Ability:Ability是應用所具備能力的抽象,也是應用程序的重要組成部分。Ability是系統調度應用的最小單元,是能夠完成一個獨立功能的組件。

搜狗高速瀏覽器截圖20240326151450.png

具體實現

1、在module.json5文件添加拓展能力,類型為卡片,并設置卡片入口srcEntrance和卡片元數據metadata。[源碼參考] 例如:"metadata": [ { "name": "ohos.extension.form", "resource": "$profile:form_config" }。

/*

 * Copyright (c) 2022 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



{

  "module": {

    "name": "entry",

    "type": "entry",

    "srcEntrance": "./ets/Application/AbilityStage.ts",

    "description": "$string:entry_desc",

    "mainElement": "MainAbility",

    "deviceTypes": [

      "default",

      "tablet",

    ],

    "deliveryWithInstall": true,

    "installationFree": false,

    "pages": "$profile:main_pages",

    "uiSyntax": "ets",

    "abilities": [

      {

        "name": "ohos.samples.formextability.MainAbility",

        "srcEntrance": "./ets/MainAbility/MainAbility.ts",

        "description": "$string:MainAbility_desc",

        "icon": "$media:icon",

        "label": "$string:MainAbility_label",

        "visible": true,

        "skills": [

          {

            "entities": [

              "entity.system.home",

            ],

            "actions": [

              "action.system.home",

            ],

          },

        ],

        "startWindowIcon": "$media:icon",

        "startWindowBackground": "$color:white"

      },

    ],

    "extensionAbilities": [

      {

        "name": "FormAbility",

        "srcEntrance": "./ets/FormAbility/FormAbility.ts",

        "label": "$string:form_FormAbility_label",

        "description": "$string:form_FormAbility_desc",

        "type": "form",

        "metadata": [

          {

            "name": "ohos.extension.form",

            "resource": "$profile:form_config",

          },

        ],

      },

    ],

  },

}

2、初始化卡片:通過實現@ohos.app.form.FormExtensionAbility卡片操作類,在卡片對象首次被創建時,初始化卡片綁定數據為空,并將卡片狀態設置為就緒狀態READY。 例如:onCreate(){ formBindingData.createFormBindingData({}) onAcquireFormState(want) { return formInfo.FormState.READY }。
3、配置卡片:用js編寫相應的卡片,將卡片配置到resources/base/profile/form_config, [源碼參考]。

{

  "forms": [

    {

      "name": "widget",

      "description": "This is a service widget.",

      "src": "./js/widget/pages/index/index",

      "formConfigAbility": "ability://ohos.samples.formextability.MainAbility",

      "window": {

        "designWidth": 720,

        "autoDesignWidth": true

      },

      "colorMode": "auto",

      "isDefault": true,

      "updateEnabled": true,

      "scheduledUpdateTime": "10:30",

      "updateDuration": 0,

      "defaultDimension": "2*4",

      "supportDimensions": [

        "2*4",

        "4*4"

      ]

    }

  ]

}
  • 修改數據卡片的訂閱條件的功能封裝在ModifyConditionIndex.ets中,源碼參考:[ModifyConditionIndex.ets]
/*

 * Copyright (c) 2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import base from '@ohos.base';

import common from '@ohos.app.ability.common';

import dataShare from '@ohos.data.dataShare';

import formBindingData from '@ohos.app.form.formBindingData';

import formInfo from '@ohos.app.form.formInfo';

import formObserver from '@ohos.app.form.formObserver';

import formProvider from '@ohos.app.form.formProvider';

import Logger from '../../common/Logger';

import { getPersistentConditionID, savePersistentConditionID } from '../../common/StatePersistence';



const TAG = '[Sample_ModifyConditionIndex]';

let dataShareHelper: dataShare.DataShareHelper;

let conditionID = '110000';

let context: common.UIAbilityContext;



function updateCardDisplayContent(runningFormInfo: formInfo.RunningFormInfo): void {

  Logger.info(`TAG updateCardDisplayContent bundle: ${runningFormInfo.bundleName}`);

  let template: dataShare.Template = {

    predicates: {

      list: `select cityTemperature as cityTemperature, cityName as cityName from TBL00 where cityId = ${conditionID}`

    },

    scheduler: ''

  };

  dataShare.createDataShareHelper(context, 'datashareproxy://ohos.samples.formextability', { isProxy: true })

    .then((data: dataShare.DataShareHelper) = > {

      dataShareHelper = data;

      dataShareHelper.addTemplate('datashareproxy://ohos.samples.formextability/test', conditionID, template);

    });



  class ProxiesType {

    key: string = '';

    subscriberId: string = '';

  };



  let proxies = [{

    key: 'datashareproxy://ohos.samples.formextability/test',

    subscriberId: conditionID

  } as ProxiesType];

  let formData: string = '';

  Logger.info(TAG, `formData: ${JSON.stringify(formData)}`);

  let formBinding = formBindingData.createFormBindingData(formData);

  formBinding['proxies'] = proxies;

  formProvider.updateForm(runningFormInfo.formId, formBinding).then(() = > {

    Logger.info(TAG, `update Form OK formData is ${JSON.stringify(formBinding)}`);

  }).catch((err: base.BusinessError< void >) = > {

    Logger.error(TAG, `update Form Failed ${JSON.stringify(err)}`);

  });

}



function modifyCondition(): void {

  let formInstanceFilterArkTS: formInfo.FormProviderFilter = {

    bundleName: 'ohos.samples.formextability',

    abilityName: 'EntryFormAbility',

    formName: 'persistentWidget',

    moduleName: 'persistentProxyForm'

  };

  let formInstanceFilterJS: formInfo.FormProviderFilter = {

    bundleName: 'ohos.samples.formextability',

    abilityName: 'EntryFormAbility',

    formName: 'persistentWidgetJS',

    moduleName: 'persistentProxyForm'

  };

  formObserver.getRunningFormInfosByFilter(formInstanceFilterArkTS).then((data: Array< formInfo.RunningFormInfo >) = > {

    Logger.info(TAG, `getRunningFormInfosByFilter data: ${JSON.stringify(data)}`);

    AppStorage.SetOrCreate('runningFormInfo', JSON.stringify(data));

    data.forEach(updateCardDisplayContent);

  }).catch((err: base.BusinessError< void >) = > {

    Logger.error(TAG, `getRunningFormInfosByFilter err is ${JSON.stringify(err)}`);

  });

  formObserver.getRunningFormInfosByFilter(formInstanceFilterJS).then((data: Array< formInfo.RunningFormInfo >) = > {

    Logger.info(TAG, `getRunningFormInfosByFilter data: ${JSON.stringify(data)}`);

    AppStorage.SetOrCreate('runningFormInfo', JSON.stringify(data));

    data.forEach(updateCardDisplayContent);

  }).catch((err: base.BusinessError< void >) = > {

    Logger.error(TAG, `getRunningFormInfosByFilter err is ${JSON.stringify(err)}`);

  });

}



@Entry

@Component

struct IndexThi {

  @State persistentConditionID: string = '';

  @State persistentSwitchFlag: boolean = true;



  aboutToAppear() {

    context = getContext(this) as common.UIAbilityContext;

    this.persistentConditionID = getPersistentConditionID(context);

    if (typeof this.persistentConditionID !== 'string' || this.persistentConditionID === '') {

      this.persistentConditionID = '110000'

    }

    this.persistentSwitchFlag = this.persistentConditionID.localeCompare('110000') === 0;

    Logger.debug(TAG, `persistentSwitchFlag : ${JSON.stringify(this.persistentSwitchFlag)}`);

  }



  aboutToDisappear() {

    savePersistentConditionID(context, this.persistentConditionID);

  }



  build() {

    Row() {

      Column({ space: 150 }) {

        Text($r('app.string.subscription_conditions'))

          .fontColor('#182431')

          .fontSize(40)

          .lineHeight(41)

          .fontWeight('Bold')

        Column() {

          Text($r('app.string.modify_subscription_conditions'))

            .fontSize(28)

            .margin({ bottom: 20 })

          Row() {

            Flex({ justifyContent: FlexAlign.SpaceEvenly }) {

              Column() {

                Text($r('app.string.city_sy'))

                  .margin({ bottom: 10 })

                Radio({ value: 'sy', group: 'modifyConditionGroup' })

                  .checked(this.persistentSwitchFlag)

                  .height(24)

                  .width(24)

                  .radioStyle({

                    checkedBackgroundColor: $r('sys.color.ohos_id_color_text_primary_activated'),

                    uncheckedBorderColor: $r('sys.color.ohos_id_color_switch_outline_off'),

                    indicatorColor: $r('sys.color.ohos_id_color_foreground_contrary')

                  })

                  .onChange((isChecked: boolean) = > {

                    Logger.info('firstRadio status is ' + isChecked);

                    if (isChecked) {

                      conditionID = '110000';

                      this.persistentConditionID = conditionID;

                      modifyCondition();

                    }

                  })

              }



              Column() {

                Text($r('app.string.city_hz'))

                  .margin({ bottom: 10 })

                Radio({ value: 'hz', group: 'modifyConditionGroup' })

                  .checked(!this.persistentSwitchFlag)

                  .height(24)

                  .width(24)

                  .radioStyle({

                    checkedBackgroundColor: $r('sys.color.ohos_id_color_text_primary_activated'),

                    uncheckedBorderColor: $r('sys.color.ohos_id_color_switch_outline_off'),

                    indicatorColor: $r('sys.color.ohos_id_color_foreground_contrary')

                  })

                  .onChange((isChecked: boolean) = > {

                    Logger.info('secondRadio status is ' + isChecked);

                    if (isChecked) {

                      conditionID = '310000';

                      this.persistentConditionID = conditionID;

                      modifyCondition();

                    }

                  })

              }

            }

          }

          .width('70%')

        }

        .width('100%')

      }

    }

    .height('100%')

  }

}

及[ModifyConditionIndex.ets]。

/*

 * Copyright (c) 2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import base from '@ohos.base';

import common from '@ohos.app.ability.common';

import formBindingData from '@ohos.app.form.formBindingData';

import formInfo from '@ohos.app.form.formInfo';

import formObserver from '@ohos.app.form.formObserver';

import formProvider from '@ohos.app.form.formProvider';

import Logger from '../../common/Logger';

import { getProcessConditionID, saveProcessConditionID } from '../../common/StatePersistence';



const TAG = '[Sample_ModifyConditionIndex]';

let conditionID = '110000';

let context: common.UIAbilityContext;



function updateCardDisplayContent(runningFormInfo: formInfo.RunningFormInfo): void {

  Logger.info(TAG, `updateCardDisplayContent bundle: ${runningFormInfo.bundleName}`);

  let proxies:Array< formBindingData.ProxyData > = [

    {

      key: 'cityName',

      subscriberId: conditionID

    },

    {

      key: 'cityTemperature',

      subscriberId: conditionID

    }

  ];

  let formBinding = formBindingData.createFormBindingData();

  formBinding['proxies'] = proxies;

  formProvider.updateForm(runningFormInfo.formId, formBinding).then(() = > {

    Logger.info(TAG, `update Form OK formData is ${JSON.stringify(formBinding)}`);

  }).catch((err: base.BusinessError< void >) = > {

    Logger.error(TAG, `update Form Failed ${JSON.stringify(err)}`);

  });

}



function modifyCondition(): void {

  let formInstanceFilter: formInfo.FormProviderFilter = {

    bundleName: 'ohos.samples.formextability',

    moduleName: 'processProxyForm'

  };

  formObserver.getRunningFormInfosByFilter(formInstanceFilter).then((data: Array< formInfo.RunningFormInfo >) = > {

    Logger.info(TAG, `getRunningFormInfosByFilter data: ${JSON.stringify(data)}`);

    AppStorage.SetOrCreate('runningFormInfo', JSON.stringify(data));

    data.forEach(updateCardDisplayContent);

  }).catch((err: base.BusinessError< void >) = > {

    Logger.error(TAG, `getRunningFormInfosByFilter err is ${JSON.stringify(err)}`);

  });

}



@Entry

@Component

struct IndexThi {

  @State processConditionID: string = '';

  @State processSwitchFlag: boolean = true;



  aboutToAppear() {

    context = getContext(this) as common.UIAbilityContext;

    this.processConditionID = getProcessConditionID(context);

    if (typeof this.processConditionID !== 'string' || this.processConditionID === '') {

      this.processConditionID = '110000'

    }

    this.processSwitchFlag = this.processConditionID.localeCompare('110000') === 0;

    Logger.debug(TAG, `persistentSwitchFlag : ${JSON.stringify(this.processSwitchFlag)}`);

  }



  aboutToDisappear() {

    saveProcessConditionID(context, this.processConditionID);

  }



  build() {

    Row() {

      Column({ space: 150 }) {

        Text($r('app.string.subscription_conditions'))

          .fontColor('#182431')

          .fontSize(40)

          .lineHeight(41)

          .fontWeight('100%')

        Column() {

          Text($r('app.string.modify_subscription_conditions'))

            .fontSize(28)

            .margin({ bottom: 20 })

          Row() {

            Flex({ justifyContent: FlexAlign.SpaceEvenly }) {

              Column() {

                Text($r('app.string.city_sy'))

                  .margin({ bottom: 10 })

                Radio({ value: 'sy', group: 'modifyConditionGroup' })

                  .height(24)

                  .width(24)

                  .radioStyle({

                    checkedBackgroundColor: $r('sys.color.ohos_id_color_text_primary_activated'),

                    indicatorColor: $r('sys.color.ohos_fa_foreground_contrary'),

                    uncheckedBorderColor: $r('sys.color.ohos_id_color_switch_outline_off') })

                  .checked(this.processSwitchFlag)

                  .onChange((isChecked: boolean) = > {

                    Logger.info('firstRadio status is ' + isChecked);

                    if (isChecked) {

                      conditionID = '110000';

                      this.processConditionID = conditionID;

                      modifyCondition();

                    }

                  })

              }



              Column() {

                Text($r('app.string.city_hz'))

                  .margin({ bottom: 10 })

                Radio({ value: 'hz', group: 'modifyConditionGroup' })

                  .height(24)

                  .width(24)

                  .checked(!this.processSwitchFlag)

                  .radioStyle({

                    checkedBackgroundColor: $r('sys.color.ohos_id_color_text_primary_activated'),

                    indicatorColor: $r('sys.color.ohos_fa_foreground_contrary'),

                    uncheckedBorderColor: $r('sys.color.ohos_id_color_switch_outline_off') })

                  .onChange((isChecked: boolean) = > {

                    Logger.info('secondRadio status is ' + isChecked);

                    if (isChecked) {

                      conditionID = '310000';

                      this.processConditionID = conditionID;

                      modifyCondition();

                    }

                  })

              }

            }

          }

          .width('70%')

        }

        .width('100%')

      }

    }

    .height('100%')

  }

}
  • 使用modifyCondition來獲取所有已經建立出的卡片對象。
  • 修改訂閱條件:使用updateCardDisplayContent遍歷所有卡片對象,并根據界面獲取的訂閱條件數據修改訂閱條件。
    • 退出頁面或應用后再次打開修改訂閱條件頁面,可以保留上次訂閱的城市選擇,源碼參考:[StatePersistence.ts]
/*

 * Copyright (c) 2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import type common from '@ohos.app.ability.common';

import fs from '@ohos.file.fs';

import Logger from './Logger';



const TAG = '[Sample_StatePersistence]';

const DATA_SIZE = 6;

const PERSISTENT_FILE_NAME = '/Persistent.txt';



function getConditionIDtoFile(context: common.Context, fileName: string): string {

  Logger.debug(TAG, 'getConditionIDtoFile call');

  if (context === undefined || context === null || typeof fileName !== 'string' || fileName === '') {

    Logger.error(TAG, `getConditionIDtoFile failed, context : ${JSON.stringify(context)}`);

    return '';

  }



  try {

    let filePath = context.filesDir + fileName;

    let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);

    let buff = new ArrayBuffer(DATA_SIZE);

    let num = fs.readSync(file.fd, buff);

    let conditionID = String.fromCharCode.apply(null, new Uint8Array(buff));

    Logger.info(TAG, `getConditionIDtoFile : ${conditionID.length} ${conditionID}, ${num} ${filePath}`);

    fs.closeSync(file);

    return conditionID;

  } catch (err) {

    Logger.error(TAG, `getConditionIDtoFile err : ${JSON.stringify(err)}`);

    return '';

  }

}



function updateConditionIDtoFile(context: common.Context, conditionID: string, fileName: string): void {

  Logger.debug(TAG, 'updateConditionIDtoFile call');

  if (context === undefined || context === null ||

  typeof conditionID !== 'string' || conditionID === '' ||

  typeof fileName !== 'string' || fileName === '') {

    Logger.error(TAG, `updateConditionIDtoFile failed, conditionID : ${JSON.stringify(conditionID)}, context : ${JSON.stringify(context)}`);

    return;

  }



  try {

    let filePath = context.filesDir + fileName;

    let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);

    let num = fs.writeSync(file.fd, conditionID);

    fs.closeSync(file);

    Logger.info(TAG, `updateConditionIDtoFile : ${conditionID}, ${num} ${filePath}`);

  } catch (err) {

    Logger.error(TAG, `updateConditionIDtoFile err : ${JSON.stringify(err)}`);

  }

}



export function getPersistentConditionID(context: common.Context): string {

  return getConditionIDtoFile(context, PERSISTENT_FILE_NAME);

}



export function savePersistentConditionID(context: common.Context, conditionID: string): void {

  updateConditionIDtoFile(context, conditionID, PERSISTENT_FILE_NAME);

}

及[StatePersistence.ts]。

/*

 * Copyright (c) 2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import type common from '@ohos.app.ability.common';

import fs from '@ohos.file.fs';

import Logger from './Logger';



const TAG = '[Sample_StatePersistence]';

const DATA_SIZE = 6;

const PROCESS_FILE_NAME = '/Process.txt';



function getConditionIDtoFile(context: common.Context, fileName: string): string {

  Logger.debug(TAG, 'getConditionIDtoFile call');

  if (context === undefined || context === null || typeof fileName !== 'string' || fileName === '') {

    Logger.error(TAG, `getConditionIDtoFile failed, context : ${JSON.stringify(context)}`);

    return '';

  }



  try {

    let filePath = context.filesDir + fileName;

    let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);

    let buff = new ArrayBuffer(DATA_SIZE);

    let num = fs.readSync(file.fd, buff);

    let conditionID = String.fromCharCode.apply(null, new Uint8Array(buff));

    Logger.info(TAG, `getConditionIDtoFile : ${conditionID.length} ${conditionID}, ${num} ${filePath}`);

    fs.closeSync(file);

    return conditionID;

  } catch (err) {

    Logger.error(TAG, `getConditionIDtoFile err : ${JSON.stringify(err)}`);

    return '';

  }

}



function updateConditionIDtoFile(context: common.Context, conditionID: string, fileName: string): void {

  Logger.debug(TAG, 'updateConditionIDtoFile call');

  if (context === undefined || context === null ||

  typeof conditionID !== 'string' || conditionID === '' ||

  typeof fileName !== 'string' || fileName === '') {

    Logger.error(TAG, `updateConditionIDtoFile failed, conditionID : ${JSON.stringify(conditionID)}, context : ${JSON.stringify(context)}`);

    return;

  }



  try {

    let filePath = context.filesDir + fileName;

    let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);

    let num = fs.writeSync(file.fd, conditionID);

    fs.closeSync(file);

    Logger.info(TAG, `updateConditionIDtoFile : ${conditionID}, ${num} ${filePath}`);

  } catch (err) {

    Logger.error(TAG, `updateConditionIDtoFile err : ${JSON.stringify(err)}`);

  }

}



export function getProcessConditionID(context: common.Context): string {

  return getConditionIDtoFile(context, PROCESS_FILE_NAME);

}



export function saveProcessConditionID(context: common.Context, conditionID: string): void {

  updateConditionIDtoFile(context, conditionID, PROCESS_FILE_NAME);

}
  • 發布數據的功能封裝在PublishIndex.ets及PushIndex.ets中,源碼參考:[PublishIndex.ets]
/*

 * Copyright (c) 2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import base from '@ohos.base';

import common from '@ohos.app.ability.common';

import dataShare from '@ohos.data.dataShare';

import dataSharePredicates from '@ohos.data.dataSharePredicates';

import formInfo from '@ohos.app.form.formInfo';

import formObserver from '@ohos.app.form.formObserver';

import prompt from '@ohos.promptAction';

import resourceManager from '@ohos.resourceManager';

import { ValuesBucket, ValueType } from '@ohos.data.ValuesBucket';

import Logger from '../../common/Logger';



const TAG = '[Sample_PublishIndex]';

let conditionCity: string;

let conditionID: ValueType = '110000';

let conditionData = '-30 ℃';

let context: common.UIAbilityContext;

let shenYang: string;

let hangZhou: string;

const formInstanceFilter: formInfo.FormProviderFilter = {

  bundleName: 'ohos.samples.formextability',

  moduleName: 'persistentProxyForm'

};



function updateRDB(context: common.UIAbilityContext): void {

  dataShare.createDataShareHelper(context, 'datashareproxy://ohos.samples.formextability', { isProxy: true })

    .then((data: dataShare.DataShareHelper) = > {

      Logger.info(TAG, `createDataShareHelper succeed, data :  ${JSON.stringify(data)}`);

      let dataShareHelper = data;

      let da = new dataSharePredicates.DataSharePredicates();

      da.equalTo('cityId', conditionID);

      let va: ValuesBucket = {

        cityName: conditionCity,

        cityTemperature: conditionData

      };

      try {

        let uri = 'datashareproxy://ohos.samples.formextability/test';

        dataShareHelper.update(uri, da, va, (err, data) = > {

          if (err !== undefined) {

            Logger.info(TAG, `update error1: code: ${err.code}, message: ${err.message} `);

            prompt.showToast(

              { message: `publish err: ${JSON.stringify(err)}`, duration: 5000 });

            return;

          }

          Logger.info(TAG, `update succeed, data : ${data}`);

          prompt.showToast(

            { message: `publish success ${conditionCity} ${conditionData}`, duration: 5000 });

        });

        dataShareHelper.notifyChange(uri);

      } catch (err) {

        Logger.info(TAG, `update error2: code: ${err.code}, message: ${err.message} `);

      }

    })

    .catch((err: base.BusinessError< void >) = > {

      Logger.info(TAG, `createDataShareHelper error: code: ${err.code}, message: ${err.message} `);

    });

}



function publish(): void {

  Logger.info(TAG, 'publish called');

  formObserver.getRunningFormInfosByFilter(formInstanceFilter).then((data: Array< formInfo.RunningFormInfo >) = > {

    Logger.info(TAG, `getRunningFormInfosByFilter data: ${JSON.stringify(data)}`);

    AppStorage.SetOrCreate('RunningFormInfo', JSON.stringify(data));

  }).catch((err: base.BusinessError< void >) = > {

    Logger.error(TAG, `getRunningFormInfosByFilter err is ${JSON.stringify(err)}`);

    prompt.showToast(

      { message: `publish err, getRunningFormInfosByFilter1 failed ${JSON.stringify(err)}`, duration: 5000 });

  });

}



@Entry

@Component

struct IndexSec {

  private inputText: string = '';



  aboutToAppear() {

    context = getContext(this) as common.UIAbilityContext;

    let syTemp = $r('app.string.city_sy');

    let hzTemp = $r('app.string.city_hz');

    let citySy: resourceManager.Resource = {

      bundleName: syTemp.bundleName,

      moduleName: syTemp.moduleName,

      id: syTemp.id

    };

    let cityHz: resourceManager.Resource = {

      bundleName: hzTemp.bundleName,

      moduleName: hzTemp.moduleName,

      id: hzTemp.id

    };

    shenYang = context.resourceManager.getStringSync(citySy);

    hangZhou = context.resourceManager.getStringSync(cityHz);

    conditionCity = shenYang;

  }



  @StorageLink('RunningFormInfo') RunningFormInfo: string = '';

  @State focus: boolean = false;



  build() {

    Row() {

      Column({ space: 200 }) {

        Column({ space: 5 }) {

          Text($r('app.string.modify_publish_data'))

            .fontColor('#182431')

            .fontSize(40)

            .lineHeight(41)

            .fontWeight('100%')

        }



        Column() {

          Column() {

            Row() {

              Text($r('app.string.selection_city'))

                .fontSize(30)

              Row() {

                Column() {

                  Text($r('app.string.city_sy'))

                    .fontSize(15)

                    .margin({ bottom: 10 })

                  Radio({ value: 'sy', group: 'cityGroup' })

                    .checked(true)

                    .height(24)

                    .width(24)

                    .radioStyle({

                      checkedBackgroundColor: $r('sys.color.ohos_id_color_text_primary_activated'),

                      uncheckedBorderColor: $r('sys.color.ohos_id_color_switch_outline_off'),

                      indicatorColor: $r('sys.color.ohos_id_color_foreground_contrary')

                    })

                    .onChange((isChecked: boolean) = > {

                      Logger.info(TAG, `sy status is ${JSON.stringify(isChecked)}`);

                      if (isChecked) {

                        conditionID = '110000';

                        conditionCity = shenYang;

                      }

                    })

                }



                Column() {

                  Text($r('app.string.city_hz'))

                    .fontSize(15)

                    .margin({ bottom: 10 })

                  Radio({ value: 'hz', group: 'cityGroup' })

                    .height(24)

                    .width(24)

                    .radioStyle({

                      checkedBackgroundColor: $r('sys.color.ohos_id_color_text_primary_activated'),

                      uncheckedBorderColor: $r('sys.color.ohos_id_color_switch_outline_off'),

                      indicatorColor: $r('sys.color.ohos_id_color_foreground_contrary')

                    })

                    .onChange((isChecked: boolean) = > {

                      Logger.info(TAG, `hz status is ${JSON.stringify(isChecked)}`);

                      if (isChecked) {

                        conditionID = '310000';

                        conditionCity = hangZhou;

                      }

                    })

                }

                .margin({ left: 20 })

              }

              .margin({ left: 10 })

            }



            Row() {

              Text($r('app.string.input_temperature'))

                .fontSize(30)

                .width(200)

                .height(60)

              TextInput({ text: '-30' })

                .fontSize(20)

                .fontColor($r('sys.color.ohos_id_color_text_primary'))

                .width(100)

                .height(40)

                .type(InputType.Normal)

                .borderRadius(16)

                .backgroundColor($r('sys.color.ohos_id_color_text_field_sub_bg'))

                .onChange((text) = > {

                  this.inputText = text;

                })

              Text('℃')

                .fontSize(30)

                .height(60)

            }

          }

          .alignItems(HorizontalAlign.Start)



          Button() {

            Text($r('app.string.published_data'))

              .fontColor($r('sys.color.ohos_id_color_foreground_contrary'))

              .fontSize($r('sys.float.ohos_id_text_size_button1'))

              .fontWeight(FontWeight.Bold)

          }

          .width(220)

          .height(40)

          .type(ButtonType.Capsule)

          .margin({ top: 20 })

          .borderRadius($r('sys.float.ohos_id_corner_radius_button'))

          .backgroundColor($r('sys.color.ohos_id_color_component_activated'))

          .onClick(() = > {

            if (Number(this.inputText) >= -40 && Number(this.inputText) <= 60) {

              Logger.info(TAG, `correct temperature is ${this.inputText}`);

              conditionData = this.inputText + ' ℃';

              publish();

              updateRDB(context);

            } else {

              Logger.info(TAG, `incorrect temperature is ${this.inputText}`);

              prompt.showToast({ message: 'Please enter the correct value from -40 to 60', duration: 5000 });

            }

          })

        }

        .height('30%')

      }

      .width('100%')

    }

    .height('100%')

  }

}

及[PushIndex.ets]。

/*

 * Copyright (c) 2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import base from '@ohos.base';

import common from '@ohos.app.ability.common';

import dataShare from '@ohos.data.dataShare';

import formInfo from '@ohos.app.form.formInfo';

import formObserver from '@ohos.app.form.formObserver';

import prompt from '@ohos.promptAction';

import Logger from '../../common/Logger';



const TAG = '[Sample_PushIndex]';

let context: common.UIAbilityContext;

let dataShareHelper: dataShare.DataShareHelper;

let uri = ('datashareproxy://ohos.samples.formextability');

let conditionCity = '';

let conditionID = '110000';

let conditionData = '-30 ℃';

let formInstanceFilter: formInfo.FormProviderFilter = {

  bundleName: 'ohos.samples.formextability',

  moduleName: 'processProxyForm'

};



function updateCardDisplayContent(runningFormInfo: formInfo.RunningFormInfo): void {

  Logger.info(TAG, `updateCardDisplayContent bundle: ${runningFormInfo.bundleName}`);

  dataShare.createDataShareHelper(context, uri, { isProxy: true }, (err, dataHelper) = > {

    Logger.info(TAG, `dataShareHelper err: ${err}`, `data: ${dataShareHelper}`);

    dataShareHelper = dataHelper;

    if (err !== undefined) {

      Logger.error(TAG, `createDataShareHelper error code: ${err.code}`, `message: ${err.message} `);

      prompt.showToast({ message: 'createDataShareHelper:' + err.message, duration: 5000 });

    } else {

      let publishedItemData: Array< dataShare.PublishedItem > = [

        { key: 'cityName', data: JSON.stringify(conditionCity), subscriberId: conditionID },

        { key: 'cityTemperature', data: JSON.stringify(conditionData), subscriberId: conditionID }

      ];

      dataShareHelper.publish(publishedItemData, 'ohos.samples.formextability').then((data: Object) = > {

        Logger.info(TAG, `publish success, data is ${JSON.stringify(data)}`);

        prompt.showToast(

          { message: `publish success ${conditionCity} ${conditionData}`, duration: 5000 });

      }).catch((err: base.BusinessError< void >) = > {

        Logger.error(TAG, `publish error: ${JSON.stringify(err)}`);

        prompt.showToast({ message: `publish err: ${JSON.stringify(err)}`, duration: 5000 });

      });

    }

  });

}



function publish(): void {

  Logger.info(TAG, 'publish called');

  formObserver.getRunningFormInfosByFilter(formInstanceFilter).then((data: Array< formInfo.RunningFormInfo >) = > {

    Logger.info(TAG, `getRunningFormInfosByFilter data: ${JSON.stringify(data)}`);

    AppStorage.SetOrCreate('runningFormInfo', JSON.stringify(data));

    data.forEach(updateCardDisplayContent);

  }).catch((err: base.BusinessError< void >) = > {

    Logger.error(TAG, `getRunningFormInfosByFilter err is ${JSON.stringify(err)}`);

    prompt.showToast(

      { message: `publish err, getRunningFormInfosByFilter failed ${JSON.stringify(err)}`, duration: 5000 });

  });

}



@Entry

@Component

struct IndexSec {

  @StorageLink('runningFormInfo') runningFormInfo: string = '';

  @State focus: boolean = false;



  aboutToAppear() {

    context = getContext(this) as common.UIAbilityContext;

    conditionCity = context.resourceManager.getStringSync($r('app.string.city_sy'));

  }



  build() {

    Row() {

      Column({ space: 200 }) {

        Column({ space: 5 }) {

          Text($r('app.string.modify_publish_data'))

            .fontColor('#182431')

            .fontSize(40)

            .lineHeight(41)

            .fontWeight('100%')

        }



        Column() {

          Column() {

            Row() {

              Text($r('app.string.selection_city'))

                .fontSize(30)

              Row() {

                Column() {

                  Text($r('app.string.city_sy'))

                    .fontSize(15)

                    .margin({ bottom: 10 })

                  Radio({ value: 'sy', group: 'cityGroup' })

                    .checked(true)

                    .height(24)

                    .width(24)

                    .radioStyle({

                      checkedBackgroundColor: $r('sys.color.ohos_id_color_text_primary_activated'),

                      indicatorColor: $r('sys.color.ohos_fa_foreground_contrary'),

                      uncheckedBorderColor: $r('sys.color.ohos_id_color_switch_outline_off') })

                    .onChange((isChecked: boolean) = > {

                      Logger.info(TAG, `sy status is ${JSON.stringify(isChecked)}`);

                      if (isChecked) {

                        conditionID = '110000';

                        conditionCity = context.resourceManager.getStringSync($r('app.string.city_sy'));

                      }

                    })

                }



                Column() {

                  Text($r('app.string.city_hz'))

                    .fontSize(15)

                    .margin({ bottom: 10 })

                  Radio({ value: 'hz', group: 'cityGroup' })

                    .height(24)

                    .width(24)

                    .radioStyle({

                      checkedBackgroundColor: $r('sys.color.ohos_id_color_text_primary_activated'),

                      indicatorColor: $r('sys.color.ohos_fa_foreground_contrary'),

                      uncheckedBorderColor: $r('sys.color.ohos_id_color_switch_outline_off') })

                    .onChange((isChecked: boolean) = > {

                      Logger.info(TAG, `hz status is ${JSON.stringify(isChecked)}`);

                      if (isChecked) {

                        conditionID = '310000';

                        conditionCity = context.resourceManager.getStringSync($r('app.string.city_hz'));

                      }

                    })

                }

                .margin({ left: 20 })

              }

              .margin({ left: 10 })

            }



            Row() {

              Text($r('app.string.input_temperature'))

                .fontSize(30)

                .width(200)

                .height(60)

              TextInput({ text: '-30' })

                .fontSize(20)

                .fontColor($r('sys.color.ohos_id_color_text_primary'))

                .width(100)

                .height(40)

                .type(InputType.Normal)

                .borderRadius(16)

                .backgroundColor($r('sys.color.ohos_id_color_text_field_sub_bg'))

                .onChange((text) = > {

                  conditionData = text;

                })

              Text('℃')

                .fontSize(30)

                .height(60)

            }

          }

          .alignItems(HorizontalAlign.Start)



          Button() {

            Text($r('app.string.published_data'))

              .fontColor($r('sys.color.ohos_id_color_foreground_contrary'))

              .fontSize($r('sys.float.ohos_id_text_size_button1'))

              .fontWeight(FontWeight.Bold)

          }

          .height(40)

          .width(220)

          .borderRadius($r('sys.float.ohos_id_corner_radius_button'))

          .backgroundColor($r('sys.color.ohos_id_color_component_activated'))

          .type(ButtonType.Capsule)

          .margin({ top: 20 })

          .onClick(() = > {

            if (Number(conditionData) >= -40 && Number(conditionData) <= 60) {

              Logger.info(TAG, `correct temperature is ${conditionData}`);

              publish();

            } else {

              Logger.info(TAG, `incorrect temperature is ${conditionData}`);

              prompt.showToast({ message: 'Please enter the correct value from -40 to 60', duration: 5000 });

            }

          })

        }

        .alignItems(HorizontalAlign.Center)

        .height('30%')

      }

      .width('100%')

    }

    .height('100%')

  }

}
更多鴻蒙開發應用知識已更新gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md參考前往。
  • [PublishIndex.ets]使用updateRDB來修改rdb數據庫中的對應數據。
  • [PushIndex.ets]使用getRunningFormInfosByFilter獲取已經建立出的卡片對象,并使用updateCardDisplayContent遍歷所有卡片對象,使用createDataShareHelper創建DataShareHelper對象,并根據界面獲取的數據信息使用publish進行數據的發布以實現發布數據的功能
  • 在dataShare模塊中,建立rdb數據庫,并提供對應update方法。
    • 在onCreate中初始化數據庫中的數據。
    • 在update中實現對應的數據更新方法。
聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • 模型
    +關注

    關注

    1

    文章

    3029

    瀏覽量

    48345
  • 鴻蒙OS
    +關注

    關注

    0

    文章

    188

    瀏覽量

    4336
收藏 人收藏

    評論

    相關推薦

    鴻蒙Stage模型--概述

    Stage模型:HarmonyOS 3.1 Develper Preview版本開始新增的模型,是目前主推且會長期演進的模型。在該模型中,由
    的頭像 發表于 01-29 13:59 ?1068次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>Stage</b><b class='flag-5'>模型</b>--概述

    Stage 模型深入解讀

    設備的遷移和協同機制。本文為大家詳細介紹 Stage 模型。 一、Stage 模型概念 應用開發模型
    的頭像 發表于 02-18 09:28 ?892次閱讀
    <b class='flag-5'>Stage</b> <b class='flag-5'>模型</b>深入解讀

    鴻蒙OS開發實例:【手擼服務卡片

    服務卡片指導文檔位于“**開發/應用模型/Stage模型開發指導/
    的頭像 發表于 03-28 22:11 ?1016次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>OS</b><b class='flag-5'>開發</b>實例:【手擼服務<b class='flag-5'>卡片</b>】

    OpenHarmony開發案例:【計步器卡片

    基于Stage模型實現帶有卡片的計步應用,用于介紹卡片開發及生命周期實現。
    的頭像 發表于 04-15 09:22 ?607次閱讀
    OpenHarmony<b class='flag-5'>開發案</b>例:【計步器<b class='flag-5'>卡片</b>】

    OpenHarmony開發案例:【電影卡片

    基于元服務卡片的能力,實現帶有卡片的電影應用,介紹卡片開發過程和生命周期實現。
    的頭像 發表于 04-15 17:53 ?1148次閱讀
    OpenHarmony<b class='flag-5'>開發案</b>例:【電影<b class='flag-5'>卡片</b>】

    鴻蒙Ability開發-Stage模型下Ability的創建和使用

    對Ability開發技術的簡單運用,更多的鴻蒙開發技術可以前往我主頁查詢,下面分享鴻蒙開發4.0技術分布(略縮圖): 高清完整版技術學習
    發表于 01-08 15:34

    Stage模型深入解讀

    的遷移和協同機制。本文為大家詳細介紹Stage模型。 一、Stage模型概念 應用開發模型是運行
    發表于 03-15 10:32

    鴻蒙元服務萬能卡片開發-stage模型和fa模型卡片區別

    一、項目類型 Application: 應用開發 Atomic Service:原子化服務開發 這里選擇Empty Ability模板創建項目。 二、Stage模型
    發表于 05-22 14:20

    OpenHarmony應用模型的構成要素與Stage優勢

    應用開發更簡單、高效。 二、Stage主推模型優勢 Stage模型之所以成為主推模型,源于其設計
    發表于 09-26 16:48

    鴻蒙Stage模型和FA模型區別

    筆者這兩個月一直在折騰分布式應用,并且分別基于 API8 的 FA 模型以及 API9 的 Stage 模型進行了開發,這兩天總算是基本開發
    的頭像 發表于 01-04 11:59 ?2360次閱讀

    Stage模型深入解讀

    形態下統一的應用組件生命周期,并支持跨設備的遷移和協同機制。本文為大家詳細介紹Stage模型。 一 Stage模型概念 應用開發
    的頭像 發表于 03-16 13:35 ?770次閱讀

    HarmonyOS 3.1上實現計步卡片

    本篇帖子是參考 Codelab 基于 Stage 模型 JS 服務卡片,使用最新 ArkTS 元服務開發的,實現帶有卡片的計步應用,用于介紹
    的頭像 發表于 05-29 11:10 ?659次閱讀

    鴻蒙OS元服務開發:【(Stage模型)設置應用主窗口】

    Stage模型下,應用主窗口由UIAbility創建并維護生命周期。在UIAbility的onWindowStageCreate回調中,通過WindowStage獲取應用主窗口,即可對其進行屬性設置等操作。還可以在應用配置文件中設置應用主窗口的屬性,如最大窗口寬度max
    的頭像 發表于 04-03 18:28 ?1085次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>OS</b>元服務<b class='flag-5'>開發</b>:【(<b class='flag-5'>Stage</b><b class='flag-5'>模型</b>)設置應用主窗口】

    HarmonyOS開發案例:【Stage模型下Ability的創建和使用】

    基于Stage模型,對Ability的創建和使用進行講解。首先在課程中我們將帶領大家使用DevEco Studio創建一個Stage模型Ability,并使用UIAbilityCont
    的頭像 發表于 05-08 14:41 ?550次閱讀
    HarmonyOS<b class='flag-5'>開發案</b>例:【<b class='flag-5'>Stage</b><b class='flag-5'>模型</b>下Ability的創建和使用】

    鴻蒙開發Ability Kit程序框架服務:FA模型切換Stage模型概述

    本文介紹如何將一個FA模型開發的聲明式范式應用切換到Stage模型
    的頭像 發表于 06-26 14:40 ?235次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>Ability Kit程序框架服務:FA<b class='flag-5'>模型</b>切換<b class='flag-5'>Stage</b><b class='flag-5'>模型</b>概述