鴻蒙開發相關知識(四)【數據持久化(用戶首選項、關系型數據庫)、通知(基礎通知、進度條通知、通知意圖)】

文章目錄

  • 一、數據持久化
    • 1、用戶首選項
      • (1)語法說明
      • (2)完整代碼示例
    • 2、關系型數據庫
      • (1)初始化數據庫
      • (2)增刪改數據
      • (3)查詢數據
      • (4)完整代碼示例
  • 二、通知
    • 1、基礎通知
      • (1)基礎使用
      • (2)通知內容類型
      • (3)完整代碼示例
    • 2、進度條通知
      • (1)基礎使用
      • (3)完整代碼示例
    • 3、通知意圖
      • (1)基礎使用
      • (2)完整代碼示例


一、數據持久化

1、用戶首選項

(1)語法說明

  • 為應用提供Key-Value鍵值型的數據處理能力,支持應用持久化輕量級數據,并對其修改和查詢。
  • Key鍵為string類型,要求非空且長度不超過80個字節。
  • 如果Value值為string類型,可以為空,不為空時長度不超過8192個字節。
  • 建議存儲的數據不超過一萬條。
  • 導入用戶首選項模塊
import dataPreferences from '@ohos.data.preferences';
  • 要獲取Preferences實例,讀取指定文件
 dataPreferences.getPreferences(this.context, 'mystore', (err, preferences) => {if (err) {console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);return;}console.info('Succeeded in getting preferences.');// 進行相關數據操作})
  • 數據操作
  • 寫入數據,如果已經存在則會覆蓋,可利用.has() 判斷是否存在
 preferences.put('startup', 'auto', (err) => {if (err) {console.error(`Failed to put data. Code:${err.code}, message:${err.message}`);return;}console.info('Succeeded in putting data.');})
  • 讀取數據,如果值為null或者非默認值類型,則返回默認數據。
 preferences.get('startup', 'default', (err, val) => {if (err) {console.error(`Failed to get value of 'startup'. Code:${err.code}, message:${err.message}`);return;}console.info(`Succeeded in getting value of 'startup'. val: ${val}.`);})
  • 刪除數據
  preferences.delete('startup', (err) => {if (err) {console.error(`Failed to delete the key 'startup'. Code:${err.code}, message:${err.message}`);return;}console.info("Succeeded in deleting the key 'startup'.");})
  • 數據持久化,應用存入數據到Preferences實例后,可以使用flush()方法實現數據持久化
preferences.flush((err) => {if (err) {console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);return;}console.info('Succeeded in flushing.');})

(2)完整代碼示例

  • ets/common/util/PreferencesUtil.ts
  • 加載實例、寫入、獲取、刪除方法
import preferences from '@ohos.data.preferences';class PreferencesUtil{prefMap: Map<string, preferences.Preferences> = new Map()async loadPreference(context, name: string){try { // 加載preferenceslet pref = await preferences.getPreferences(context, name)this.prefMap.set(name, pref)console.log('testTag', `加載Preferences[${name}]成功`)} catch (e) {console.log('testTag', `加載Preferences[${name}]失敗`, JSON.stringify(e))}}async putPreferenceValue(name: string, key: string, value: preferences.ValueType){if (!this.prefMap.has(name)) {console.log('testTag', `Preferences[${name}]尚未初始化!`)return}try {let pref = this.prefMap.get(name)// 寫入數據await pref.put(key, value)// 刷盤await pref.flush()console.log('testTag', `保存Preferences[${name}.${key} = ${value}]成功`)} catch (e) {console.log('testTag', `保存Preferences[${name}.${key} = ${value}]失敗`, JSON.stringify(e))}}async getPreferenceValue(name: string, key: string, defaultValue: preferences.ValueType){if (!this.prefMap.has(name)) {console.log('testTag', `Preferences[${name}]尚未初始化!`)return}try {let pref = this.prefMap.get(name)// 讀數據let value = await pref.get(key, defaultValue)console.log('testTag', `讀取Preferences[${name}.${key} = ${value}]成功`)return value} catch (e) {console.log('testTag', `讀取Preferences[${name}.${key} ]失敗`, JSON.stringify(e))}}
}const preferencesUtil = new PreferencesUtil()export default preferencesUtil as PreferencesUtil
  • ets/entryability/EntryAbility.ets
  • 應用啟動時調用加載實例方法
import UIAbility from '@ohos.app.ability.UIAbility';
import PreferencesUtil from '../common/util/PreferencesUtil'export default class EntryAbility extends UIAbility {async onCreate(want, launchParam) {hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate running');// 加載Preferencesawait PreferencesUtil.loadPreference(this.context, 'MyPreferences')}
}
  • ets/pages/Index.ets
  • 頁面出現前(aboutToAppear())獲取實例并賦值
import IndexFontSizePanel from '../views/IndexFontSizePanel'
import PreferencesUtil from '../common/util/PreferencesUtil'@Entry
@Component
struct Index {@State message: string = '頁面列表'@State showPanel: boolean = false@Provide fontSize: number = 16async aboutToAppear(){this.fontSize = await PreferencesUtil.getPreferenceValue('MyPreferences', 'IndexFontSize', 16) as number}build() {Column() {// 字體修改面板if(this.showPanel){IndexFontSizePanel().transition({translate: { y: 115 }})}}.width('100%').height('100%')}}
  • views/IndexFontSizePanel.ets
  • onChange 方法中修改實例值
import PreferencesUtil from '../common/util/PreferencesUtil'@Component
export default struct IndexFontSizePanel {@Consume fontSize: numberfontSizLabel: object = {14: '小',16: '標準',18: '大',20: '特大',}build() {Column() {Text(this.fontSizLabel[this.fontSize]).fontSize(20)Row({ space: 5 }) {Text('A').fontSize(14).fontWeight(FontWeight.Bold)Slider({min: 14,max: 20,step: 2,value: this.fontSize}).showSteps(true).trackThickness(6).layoutWeight(1).onChange(val => {// 修改字體大小this.fontSize = val// 寫入PreferencesPreferencesUtil.putPreferenceValue('MyPreferences', 'IndexFontSize', val)})Text('A').fontSize(20).fontWeight(FontWeight.Bold)}.width('100%')}.width('100%').padding(15).backgroundColor('#fff1f0f0').borderRadius(20)}
}

2、關系型數據庫

(1)初始化數據庫

  • a、導入關系型數據庫模塊
import relationalStore from '@ohos.data.relationalStore';
  • b、初始化數據庫表
  • rdb配置
const STORE_CONFIG = {name: 'RdbTest.db', // 數據庫文件名securityLevel: relationalStore.SecurityLevel.S1 // 數據庫安全級別
};
  • 初始化表的SQL
// 建表Sql語句
const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)';
  • 獲取rdb,執行SQL,后續的所有增刪改查都是使用rdbStore對象
relationalStore.getRdbStore(this.context, STORE_CONFIG, (err, store) => {if (err) {console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);return;}console.info(`Succeeded in getting RdbStore.`);store.executeSql(SQL_CREATE_TABLE); // 創建數據表// 這里執行數據庫的增、刪、改、查等操作});

(2)增刪改數據

  • a.新增數據
const valueBucket = {'NAME': 'Lisa','AGE': 18,'SALARY': 100.5,'CODES': new Uint8Array([1, 2, 3, 4, 5])
};
//EMPLOYEE 數據表名
store.insert('EMPLOYEE', valueBucket, (err, rowId) => {if (err) {console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`);return;}console.info(`Succeeded in inserting data. rowId:${rowId}`);
})
  • b.修改數據
const valueBucket = {'NAME': 'Rose','AGE': 22,
};
// 創建表'EMPLOYEE'的predicates
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
// 匹配表'EMPLOYEE'中'NAME'為'Lisa'的字段
predicates.equalTo('NAME', 'Lisa'); 
store.update(valueBucket, predicates, (err, rows) => {if (err) {console.error(`Failed to update data. Code:${err.code}, message:${err.message}`);return;}console.info(`Succeeded in updating data. row count: ${rows}`);
})
  • c.刪除數據
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.equalTo('NAME', 'Lisa');
store.delete(predicates, (err, rows) => {if (err) {console.error(`Failed to delete data. Code:${err.code}, message:${err.message}`);return;}console.info(`Delete rows: ${rows}`);
})

(3)查詢數據

  • a.查詢數據、返回一個ResultSet結果集
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.equalTo('NAME', 'Rose');
let result = await store.query(predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'])
  • b.解析結果
// 準備數組保存結果
let tasks:any[]=[]
//循環遍歷結果集,判斷結果是否遍歷到最后一行
while(!result.isAtLastRow){//指針移動到下一行數據result.goToNextRow()//根據字段名獲取字段index,從而獲取字段值let id = result.getLong(result.getColumnIndex('ID'));let name = result.getString(result.getColumnIndex('NAME'));tasks.push({id,name})
}

(4)完整代碼示例

  • ets/model/TaskModel.ets
import relationalStore from '@ohos.data.relationalStore';
import TaskInfo from '../viewmodel/TaskInfo';class TaskModel {private rdbStore: relationalStore.RdbStoreprivate tableName: string = 'TASK'/*** 初始化任務表*/initTaskDB(context){// 1.rdb配置const config = {name: 'MyApplication.db',securityLevel: relationalStore.SecurityLevel.S1}// 2.初始化SQL語句const sql = `CREATE TABLE IF NOT EXISTS TASK (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT NOT NULL,FINISHED bit)`// 3.獲取rdbrelationalStore.getRdbStore(context, config, (err, rdbStore) => {if(err){console.log('testTag', '獲取rdbStore失敗!')return}// 執行SqlrdbStore.executeSql(sql)console.log('testTag', '創建task表成功!')// 保存rdbStorethis.rdbStore = rdbStore})}/*** 查詢任務列表*/async getTaskList(){// 1.構建查詢條件let predicates = new relationalStore.RdbPredicates(this.tableName)// 2.查詢let result = await this.rdbStore.query(predicates, ['ID', 'NAME', 'FINISHED'])// 3.解析查詢結果// 3.1.定義一個數組,組裝最終的查詢結果let tasks: TaskInfo[] = []// 3.2.遍歷封裝while(!result.isAtLastRow){// 3.3.指針移動到下一行result.goToNextRow()// 3.4.獲取數據let id = result.getLong(result.getColumnIndex('ID'))let name = result.getString(result.getColumnIndex('NAME'))let finished = result.getLong(result.getColumnIndex('FINISHED'))// 3.5.封裝到數組tasks.push({id, name, finished: !!finished})}console.log('testTag', '查詢到數據:', JSON.stringify(tasks))return tasks}/*** 添加一個新的任務* @param name 任務名稱* @returns 任務id*/addTask(name: string): Promise<number>{return this.rdbStore.insert(this.tableName, {name, finished: false})}/*** 根據id更新任務狀態* @param id 任務id* @param finished 任務是否完成*/updateTaskStatus(id: number, finished: boolean) {// 1.要更新的數據let data = {finished}// 2.更新的條件let predicates = new relationalStore.RdbPredicates(this.tableName)predicates.equalTo('ID', id)// 3.更新操作return this.rdbStore.update(data, predicates)}/*** 根據id刪除任務* @param id 任務id*/deleteTaskById(id: number){// 1.刪除的條件let predicates = new relationalStore.RdbPredicates(this.tableName)predicates.equalTo('ID', id)// 2.刪除操作return this.rdbStore.delete(predicates)}
}let taskModel = new TaskModel();export default taskModel as TaskModel;
  • ets/entryability/EntryAbility.ets
  • 應用啟動時調用初始化
import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import TaskModel from '../model/TaskModel';export default class EntryAbility extends UIAbility {async onCreate(want, launchParam) {// 初始化任務表TaskModel.initTaskDB(this.context)}
}
  • 頁面調用方法查詢、添加數據
import TaskModel from '../../model/TaskModel'// 總任務數量@Link totalTask: number@Link finishTask: number// 任務數組@State tasks: TaskInfo[] = []aboutToAppear(){// 查詢任務列表console.log('testTag', '初始化組件,查詢任務列表')TaskModel.getTaskList().then(tasks => {this.tasks = tasks// 更新任務狀態this.handleTaskChange()})}handleTaskChange(){// 1.更新任務總數量this.totalTask = this.tasks.length// 2.更新已完成任務數量this.finishTask = this.tasks.filter(item => item.finished).length}
  handleAddTask(name: string){// 1.新增任務TaskModel.addTask(name).then(id => {console.log('testTag', '處理新增任務: ', name)// 回顯到數組頁面this.tasks.push(new TaskInfo(id, name))// 2.更新任務完成狀態this.handleTaskChange()// 3.關閉對話框this.dialogController.close()}).catch(error => console.log('testTag', '新增任務失敗:', name, JSON.stringify(error)))}
@Builder DeleteButton(index: number, id: number){Button(){Image($r('app.media.ic_public_delete_filled')).fillColor(Color.White).width(20)}.width(40).height(40).type(ButtonType.Circle).backgroundColor(Color.Red).margin(5).onClick(() => {// 刪除任務TaskModel.deleteTaskById(id).then(() => {this.tasks.splice(index, 1)console.log('testTag', `嘗試刪除任務,index: ${index}`)this.handleTaskChange()}).catch(error => console.log('testTag', '刪除任務失敗,id = ', id, JSON.stringify(error)))})}

二、通知

1、基礎通知

  • 應用可以通過通知接口發送通知消息,提醒用戶關注應用中變化。
  • 用戶可以在通知欄查看和操作通知內容

(1)基礎使用

  • 導入notification模塊
import notificationManager from '@ohos.notificationManager';
  • 構建通知請求
let request: notificationManager.NotificationRequest = {id: 1, content: {// 通知內容:...}},showDeliveryTime: true, // 是否顯示分發時間deliveryTime: new Date().getTime(), // 通知發送時間groupName: 'wechat', // 組通知名稱slotType: notify.SlotType.SOCIAL_COMMUNICATION  // 通道類型...   //其它屬性查看相關文檔
}
  • 發布通知
notificationManager.publish(request, (err) => {if (err) {console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);return;}console.info('Succeeded in publishing notification.');
});
  • 取消通知
// 取消 id=10 的通知
notificationManager.cancel(10)
// 取消當前應用所有通知
notificationManager.cancelAll()

(2)通知內容類型

  • 普通文本類型
let notificationRequest = {id: 1,content: {contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本類型通知normal: {title: '通知標題',text: '通知內容詳情',additionalText: '通知附加內容',}}
}
  • 長文本類型
let notificationRequest = {id: 1,content: {contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // 長文本類型通知longText: {title: '通知標題',text: '通知內容詳情',additionalText: '通知附加內容',longText: '通知中的長文本、很長很長。。。',briefText: '通知概要總結',expandedTitle: '通知展開時的標題',}}
}
  • 多行文本類型
let notificationRequest = {id: 1,content: {contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本類型通知multiLine: {title: '通知標題',text: '通知內容詳情',additionalText: '通知附加內容',briefText: '通知概要總結',longTitle: '展開時的標題,有多行,我很寬',lines: ['第一行', '第二行', '第三行', '第四行'],}}
}
  • 圖片類型
// 需要獲取圖片PixelMap信息
let imagePixelMap: PixelMap = undefined; 
let notificationRequest: notificationManager.NotificationRequest = {id: 1,content: {contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,picture: {title: '通知標題',text: '通知內容詳情',additionalText: '通知附加內容',briefText: '通知概要總結',expandedTitle: '通知展開時的標題',picture: imagePixelMap}}
};
  • 獲取圖片PixelMap信息
async aboutToAppear() {// 獲取資源管理器let rm = getContext(this).resourceManager;// 讀取圖片let file = await rm.getMediaContent($r('app.media.watchGT4'))// 創建PixelMapimage.createImageSource(file.buffer).createPixelMap().then(value => this.pixel = value).catch(reason => console.log('testTag', '加載圖片異常', JSON.stringify(reason)))
}

(3)完整代碼示例

import notify from '@ohos.notificationManager'
import image from '@ohos.multimedia.image'@Entry
@Component
struct NotificationPage {// 全局任務ididx: number = 100// 圖象pixel: PixelMapasync aboutToAppear() {// 獲取資源管理器let rm = getContext(this).resourceManager;// 讀取圖片let file = await rm.getMediaContent($r('app.media.watchGT4'))// 創建PixelMapimage.createImageSource(file.buffer).createPixelMap().then(value => this.pixel = value).catch(reason => console.log('testTag', '加載圖片異常', JSON.stringify(reason)))}build() {Column({space: 20}) {Button(`發送normalText通知`).onClick(() => this.publishNormalTextNotification())Button(`發送longText通知`).onClick(() => this.publishLongTextNotification())Button(`發送multiLine通知`).onClick(() => this.publishMultiLineNotification())Button(`發送Picture通知`).onClick(() => this.publishPictureNotification())}.width('100%').height('100%').padding(5).backgroundColor('#f1f2f3')}//通知普通文本publishNormalTextNotification() {let request: notify.NotificationRequest = {id: this.idx++,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: '通知標題' + this.idx,text: '通知內容詳情',additionalText: '通知附加內容'}},showDeliveryTime: true,deliveryTime: new Date().getTime(),groupName: 'wechat',slotType: notify.SlotType.SOCIAL_COMMUNICATION}this.publish(request)}//通知長文本publishLongTextNotification() {let request: notify.NotificationRequest = {id: this.idx++,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_LONG_TEXT,longText: {title: '通知標題' + this.idx,text: '通知內容詳情',additionalText: '通知附加內容',longText: '通知中的長文本,我很長,我很長,我很長,我很長,我很長,我很長,我很長',briefText: '通知概要和總結',expandedTitle: '通知展開時的標題' + this.idx}}}this.publish(request)}//通知多行文本publishMultiLineNotification() {let request: notify.NotificationRequest = {id: this.idx++,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_MULTILINE,multiLine: {title: '通知標題' + this.idx,text: '通知內容詳情',additionalText: '通知附加內容',briefText: '通知概要和總結',longTitle: '展開時的標題,我很寬,我很寬,我很寬',lines: ['第一行','第二行','第三行','第四行',]}}}this.publish(request)}//通知圖片類型publishPictureNotification() {let request: notify.NotificationRequest = {id: this.idx++,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_PICTURE,picture: {title: '通知標題' + this.idx,text: '通知內容詳情',additionalText: '通知附加內容',briefText: '通知概要和總結',expandedTitle: '展開后標題' + this.idx,picture: this.pixel}}}this.publish(request)}// 發送文本private publish(request: notify.NotificationRequest) {notify.publish(request).then(() => console.log('notify test', '發送通知成功')).then(reason => console.log('notify test', '發送通知失敗', JSON.stringify(reason)))}
}

2、進度條通知

  • 進度條通知會展示一個動態的進度條,主要用于文件下載、長任務處理的進度顯示。

(1)基礎使用

  • 判斷當前系統是否支持進度條模板
NotificationManager.isSupportTemplate('downloadTemplate').then((data) => {console.info(`[ANS] isSupportTemplate success`);let isSupportTpl: boolean = data; // isSupportTpl的值為true表示支持支持downloadTemplate模板類通知,false表示不支持// ...
}).catch((err) => {console.error(`[ANS] isSupportTemplate failed, error[${err}]`);
});
  • 通知模板
  • 模板名稱,必須是 downloadTemplate
let template = {name:'downloadTemplate',data: {title: '標題:',fileName: 'music.mp4', // 文件名progressValue: 30, //進度條當前值progressMaxValue:100, // 進度條最大值}
}
  • 通知請求
let notificationRquest = {id: 1,slotType: notify.SlotType.OTHER_TYPES,template: template, //進度條模板content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: template.data.title + template.data.fileName,text: "sendTemplate",additionalText: "30%"}},deliveryTime: new Date().getTime(),showDeliveryTime: true
}
  • 發送通知,與基礎通知相同

(3)完整代碼示例

import notify from '@ohos.notificationManager'
import promptAction from '@ohos.promptAction'enum DownloadState {NOT_BEGIN = '未開始',DOWNLOADING = '下載中',PAUSE = '已暫停',FINISHED = '已完成',
}@Component
export default struct DownloadCard {// 下載進度@State progressValue: number = 0progressMaxValue: number = 100// 任務狀態@State state: DownloadState = DownloadState.NOT_BEGIN// 下載的文件名filename: string = '圣誕星.mp4'// 模擬下載的任務的idtaskId: number = -1// 通知idnotificationId: number = 999isSupport: boolean = falseasync aboutToAppear(){// 1.判斷當前系統是否支持進度條模板this.isSupport = await notify.isSupportTemplate('downloadTemplate')}build() {Row({ space: 10 }) {Image($r('app.media.ic_files_video')).width(50)Column({ space: 5 }) {Row() {Text(this.filename)Text(`${this.progressValue}%`).fontColor('#c1c2c1')}.width('100%').justifyContent(FlexAlign.SpaceBetween)Progress({value: this.progressValue,total: this.progressMaxValue,})Row({ space: 5 }) {Text(`${(this.progressValue * 0.43).toFixed(2)}MB`).fontSize(14).fontColor('#c1c2c1')Blank()if (this.state === DownloadState.NOT_BEGIN) {Button('開始').downloadButton().onClick(() => this.download())} else if (this.state === DownloadState.DOWNLOADING) {Button('取消').downloadButton().backgroundColor('#d1d2d3').onClick(() => this.cancel())Button('暫停').downloadButton().onClick(() => this.pause())} else if (this.state === DownloadState.PAUSE) {Button('取消').downloadButton().backgroundColor('#d1d2d3').onClick(() => this.cancel())Button('繼續').downloadButton().onClick(() => this.download())} else {Button('打開').downloadButton().onClick(() => this.open())}}.width('100%')}.layoutWeight(1)}.width('100%').borderRadius(20).padding(15).backgroundColor(Color.White)}cancel() {// 取消定時任務if(this.taskId > 0){clearInterval(this.taskId);this.taskId = -1}// 清理下載任務進度this.progressValue = 0// 標記任務狀態:未開始this.state = DownloadState.NOT_BEGIN// 取消通知notify.cancel(this.notificationId)}download() {// 清理舊任務if(this.taskId > 0){clearInterval(this.taskId);}// 開啟定時任務,模擬下載this.taskId = setInterval(() => {// 判斷任務進度是否達到100if(this.progressValue >= 100){// 任務完成了,應該取消定時任務clearInterval(this.taskId)this.taskId = -1// 并且標記任務狀態為已完成this.state = DownloadState.FINISHED// 發送通知this.publishDownloadNotification()return}// 模擬任務進度變更this.progressValue += 2// 發送通知this.publishDownloadNotification()}, 500)// 標記任務狀態:下載中this.state = DownloadState.DOWNLOADING}pause() {// 取消定時任務if(this.taskId > 0){clearInterval(this.taskId);this.taskId = -1}// 標記任務狀態:已暫停this.state = DownloadState.PAUSE// 發送通知this.publishDownloadNotification()}open() {promptAction.showToast({message: '功能未實現'})}publishDownloadNotification(){// 1.判斷當前系統是否支持進度條模板if(!this.isSupport){// 當前系統不支持進度條模板return}// 2.準備進度條模板的參數let template = {name: 'downloadTemplate',data: {progressValue: this.progressValue,progressMaxValue: this.progressMaxValue}}let request: notify.NotificationRequest = {id: this.notificationId,template: template,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: this.filename + ':  ' + this.state,text: '',additionalText: this.progressValue + '%'}}}// 3.發送通知notify.publish(request).then(() => console.log('test', '通知發送成功')).catch(reason => console.log('test', '通知發送失敗!', JSON.stringify(reason)))}
}@Extend(Button) function downloadButton() {.width(75).height(28).fontSize(14)
}

3、通知意圖

  • 我們可以給通知或其中的按鈕設置的行為意圖(Want
  • 從而實現拉起應用組件或發布公共事件等能力。

(1)基礎使用

  • 導入模塊
import NotificationManager from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
  • 意圖行為信息
let wantAgentInfo = {wants: [{deviceId: '',bundleName: 'com.example.test',abilityName: 'com.example.test.MainAbility',action: '',entities: [],uri: '',parameters: {}}],operationType: wantAgent.OperationType.START_ABILITY,requestCode: 0,wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
}
  • 創建wantAgent實例
 // 用于保存創建成功的WantAgent對象,后續使用其完成觸發的動作。
let wantAgentObj = null;wantAgent.getWantAgent(wantAgentInfo, (err, data) => {if (err) {console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err));} else {console.info('[WantAgent]getWantAgent success');wantAgentObj = data;}
});
  • 通知請求
let notificationRequest = {content: {// ....},id: 1,label: 'TEST',wantAgent: wantAgentObj,
}

(2)完整代碼示例

import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'
import promptAction from '@ohos.promptAction'@Component
export default struct DownloadCard {// 存放wantAgent實例wantAgentInstance: WantAgentasync aboutToAppear(){// 1.判斷當前系統是否支持進度條模板this.isSupport = await notify.isSupportTemplate('downloadTemplate')// 2.創建拉取當前應用的行為意圖// 2.1.創建wantInfo信息let wantInfo: wantAgent.WantAgentInfo = {wants: [{bundleName: 'com.example.myapplication',abilityName: 'EntryAbility',}],requestCode: 0,operationType: wantAgent.OperationType.START_ABILITY,wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]}// 2.2.創建wantAgent實例this.wantAgentInstance = await wantAgent.getWantAgent(wantInfo)}build() {···· // 同進度條通知代碼示例}open() {promptAction.showToast({message: '功能未實現'})}publishDownloadNotification(){// 1.判斷當前系統是否支持進度條模板if(!this.isSupport){// 當前系統不支持進度條模板return}// 2.準備進度條模板的參數let template = {name: 'downloadTemplate',data: {progressValue: this.progressValue,progressMaxValue: this.progressMaxValue}}let request: notify.NotificationRequest = {id: this.notificationId,template: template,// 通知意圖wantAgent: this.wantAgentInstance,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: this.filename + ':  ' + this.state,text: '',additionalText: this.progressValue + '%'}}}// 3.發送通知notify.publish(request).then(() => console.log('test', '通知發送成功')).catch(reason => console.log('test', '通知發送失敗!', JSON.stringify(reason)))}
}@Extend(Button) function downloadButton() {.width(75).height(28).fontSize(14)
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/712275.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/712275.shtml
英文地址,請注明出處:http://en.pswp.cn/news/712275.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

《2023年勒索軟件攻擊態勢報告》

獲取方式&#xff1a; 鏈接&#xff1a;https://pan.baidu.com/s/1zd-yVsuGwJADyyGNFR_TIQ?pwd2lo0 提取碼&#xff1a;2lo0

探索數據結構:解鎖計算世界的密碼

?? 歡迎大家來到貝蒂大講堂?? &#x1f388;&#x1f388;養成好習慣&#xff0c;先贊后看哦~&#x1f388;&#x1f388; 所屬專欄&#xff1a;數據結構與算法 貝蒂的主頁&#xff1a;Betty‘s blog 前言 隨著應用程序變得越來越復雜和數據越來越豐富&#xff0c;幾百萬、…

600萬訂單每秒Disruptor +SpringBoot,如何解決消息不丟失?

尼恩說在前面 在40歲老架構師 尼恩的讀者交流群(50)中&#xff0c;最近有小伙伴拿到了一線互聯網企業如得物、阿里、滴滴、極兔、有贊、shein 希音、百度、網易的面試資格&#xff0c;遇到很多很重要的面試題&#xff1a; Disruptor 官方說能達到每秒600w OPS訂單處理能力&…

Java——Object

1.Object萬類之祖 1.1 Object類型的概述 Object類是所有類型的頂層父類&#xff0c;所有類型的直接或者間接的父類&#xff1b;所有的類型中都含有Object類中的所有方法。 隨意定義一個類型,不手動顯式定義其父類&#xff0c;那么這個類的父類就是Object類 public Object() …

【C語言】指針初階2.0版本

這篇博文我們來繼續學習指針的其他內容 指針2.0 傳值調用與傳址調用傳值調用傳址調用 一維數組與指針理解數組名使用指針深入理解一維數組 二級指針指針數組二維數組與指針 傳值調用與傳址調用 在開始之前&#xff0c;我們需要先了解這個概念&#xff0c;后面才能夠正常的學習…

利用 Python 抓取數據探索汽車市場趨勢

一、引言 隨著全球對環境保護意識的增強和技術的進步&#xff0c;新能源汽車作為一種環保、高效的交通工具&#xff0c;正逐漸受到人們的關注和青睞。在這個背景下&#xff0c;對汽車市場的數據進行分析和研究顯得尤為重要。 本文將介紹如何利用 Python 編程語言&#xff0c;結…

VSCode上搭建C/C++開發環境(vscode配置c/c++環境)Windows系統---保姆級教程

引言勸退 VSCode&#xff0c;全稱為Visual Studio Code&#xff0c;是由微軟開發的一款輕量級&#xff0c;跨平臺的代碼編輯器。大家能來搜用VSCode配置c/c&#xff0c;想必也知道VSCode的強大&#xff0c;可以手握一個VSCode同時編寫如C&#xff0c;C&#xff0c;C#&#xff…

微服務day02-Ribbon負載均衡與Nacos安裝與入門

一.Ribbon負載均衡 在上一節中&#xff0c;我們通過在RestTemplte實例中加上了注解 LoadBalanced,表示將來由RestTemplate發起的請求會被Ribbon攔截和處理&#xff0c;實現了訪問服務時的負載均衡&#xff0c;那么他是如何實現的呢&#xff1f; 1.1 Ribbon負載均衡的原理 Rib…

鏈表的歸并排序-LeetCode(Python版)

雙指針歸并排序&#xff01;圖解排序鏈表&#xff01;-知乎 class ListNode(object):def __init__(self, val0, nextNone):self.val valself.next nextclass Solution(object):def find_mid(self, head): # 快慢指針slow, fast head, headwhile fast.next and fast.next.n…

linux 硬盤存儲剩余容量自動化監控+報警通知

linux 硬盤存儲剩余容量自動化監控報警通知 編寫shell腳本 #!/bin/bash# 獲取系統存儲大小&#xff08;單位為GB&#xff09; storage_size$(df -h / | awk NR2 {print $4} | sed s/G//)# 閾值&#xff08;小于10GB觸發報警&#xff09; threshold10# 釘釘機器人 Webhook UR…

LabVIEW非接觸式電阻抗層析成像系統

LabVIEW非接觸式電阻抗層析成像系統 非接觸式電阻抗層析成像&#xff08;NEIT&#xff09;技術以其無輻射、非接觸、響應速度快的特點&#xff0c;為實時監測提供了新的解決方案。基于LabVIEW的電阻抗層析成像系統&#xff0c;實現了數據的在線采集及實時成像&#xff0c;提高…

代碼隨想錄算法訓練營第四十四天|139.單詞拆分、56.攜帶礦石資源

139.單詞拆分 思路&#xff1a;將字符串s看作為背包容量&#xff0c;從字符串中獲取物品&#xff0c;剛好滿足背包容量的過程&#xff0c;因為可以從字符串中多次取值&#xff0c;相當于物品的數量是不限制&#xff0c;這就是一個完全背包的問題&#xff01;這個題有個關鍵點&a…

Python中的windows路徑問題

在Python中處理Windows路徑時,經常會遇到一些特殊的問題。這主要是因為Windows和大多數其他操作系統(如Linux和macOS)使用不同的路徑分隔符。在Windows中,路徑使用反斜杠(\)作為分隔符,而在其他操作系統中,路徑使用正斜杠(/)作為分隔符。 以下是在Python中處理Windo…

Java SE:多線程(Thread)

1. 線程兩個基本概念 并發&#xff1a;即線程交替運行多個指令并行&#xff1a;即多個線程同時運行指令 并發并行不矛盾&#xff0c;兩者可同時發生&#xff0c;即多個線程交替運行指令 2. 多線程3種實現方式 2.1 直接創建線程對象 /*** 方式1&#xff1a;* 1. 創建thread類的…

mybatis plus 深入學習 【Base Mapper】的方法 【IService】的方法

mybatis plus 深入學習 常見注解 1.TableName 描述&#xff1a;表名注解&#xff0c;標識實體類對應的表使用位置&#xff1a;實體類 TableName("sys_user") public class User {private Long id;private String name;private Integer age;private String email;…

【Linux系統化學習】信號的保存

目錄 阻塞信號 信號處理常見方式概覽 信號的其他相關概念 在內核中的表示 sigset_t 信號集操作函數 sigprocmask函數 sigpending函數 信號的捕捉 內核如何實現信號的捕捉 sigaction函數 可重入函數 volatile 阻塞信號 信號處理常見方式概覽 當信號來臨時&#x…

c++算法入門教程(2)

C是一種功能強大且廣泛應用的編程語言&#xff0c;對于想要深入學習編程和算法的人來說&#xff0c;掌握C是一個重要的里程碑。本文將帶你逐步了解C編程的基礎知識&#xff0c;并介紹一些常見的算法和編程技巧幫你入門c算法。 ?在c算法入門教程(1) 中&#xff0c;我講解了什么…

GEE:使用Sigmoid激活函數對單波段圖像進行變換(以NDVI為例)

作者:CSDN @ _養樂多_ 本文將介紹在 Google Earth Engine (GEE)平臺上,對任意單波段影像進行 Sigmoid 變換的代碼。并以對 NDVI 影像像素值的變換為例。 文章目錄 一、Sigmoid激活函數1.1 什么是 Sigmoid 激活函數1.2 用到遙感圖像上有什么用?二、代碼鏈接三、完整代碼一…

查詢每個會話使用內存大小(DM8達夢數據庫)

DM8達夢數據庫查詢每個會話使用內存大小 1 環境介紹2 查詢每個sql會話使用內存大小3 達夢數據庫學習使用列表 1 環境介紹 在某些環境數據庫內存增長到服務器內存用完,發生OOM事件,可以分析sql會話使用內存大小; 2 查詢每個sql會話使用內存大小 --創建SQL會話占用內存記錄表 …

共享棧的C語言實現

共享棧&#xff1a;所謂共享棧就是為了節省空間&#xff0c;讓兩個棧共享一片連續的存儲空間&#xff0c;兩個棧從這片連續的共享空間的兩端向中間擴充自己的存儲空間&#xff0c;設這片存儲空間的大小為maxSize&#xff0c;采用棧頂指針始終指向當前棧頂元素的方式來實現共享棧…