一、数据持久化
1、用户首选项
(1)语法说明
为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。 Key
键为string
类型,要求非空且长度不超过80 个字节。如果Value
值为string
类型,可以为空,不为空时长度不超过8192个字节。 建议存储的数据不超过一万条。 导入用户首选项模块
import dataPreferences from '@ohos.data.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 {
let 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' ) ;
await 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 = 16
async 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: number
fontSizLabel: 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
PreferencesUtil. putPreferenceValue ( 'MyPreferences' , 'IndexFontSize' , val)
} )
Text ( 'A' ) . fontSize ( 20 ) . fontWeight ( FontWeight. Bold)
} . width ( '100%' )
}
. width ( '100%' )
. padding ( 15 )
. backgroundColor ( '#fff1f0f0' )
. borderRadius ( 20 )
}
}
2、关系型数据库
(1)初始化数据库
import relationalStore from '@ohos.data.relationalStore' ;
const STORE_CONFIG = {
name: 'RdbTest.db' ,
securityLevel: relationalStore. SecurityLevel. S1
} ;
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)增删改数据
const valueBucket = {
'NAME' : 'Lisa' ,
'AGE' : 18 ,
'SALARY' : 100.5 ,
'CODES' : new Uint8Array ( [ 1 , 2 , 3 , 4 , 5 ] )
} ;
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} ` ) ;
} )
const valueBucket = {
'NAME' : 'Rose' ,
'AGE' : 22 ,
} ;
let predicates = new relationalStore . RdbPredicates ( 'EMPLOYEE' ) ;
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} ` ) ;
} )
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)查询数据
let predicates = new relationalStore . RdbPredicates ( 'EMPLOYEE' ) ;
predicates. equalTo ( 'NAME' , 'Rose' ) ;
let result = await store. query ( predicates, [ 'ID' , 'NAME' , 'AGE' , 'SALARY' , 'CODES' ] )
let tasks: any [ ] = [ ]
while ( ! result. isAtLastRow) {
result. goToNextRow ( )
let id = result. getLong ( result. getColumnIndex ( 'ID' ) ) ;
let name = result. getString ( result. getColumnIndex ( 'NAME' ) ) ;
tasks. push ( { id, name} )
}
(4)完整代码示例
import relationalStore from '@ohos.data.relationalStore' ;
import TaskInfo from '../viewmodel/TaskInfo' ;
class TaskModel {
private rdbStore: relationalStore. RdbStore
private tableName: string = 'TASK'
initTaskDB ( context) {
const config = {
name: 'MyApplication.db' ,
securityLevel: relationalStore. SecurityLevel. S1
}
const sql = ` CREATE TABLE IF NOT EXISTS TASK (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
FINISHED bit
) `
relationalStore. getRdbStore ( context, config, ( err, rdbStore) => {
if ( err) {
console . log ( 'testTag' , '获取rdbStore失败!' )
return
}
rdbStore. executeSql ( sql)
console . log ( 'testTag' , '创建task表成功!' )
this . rdbStore = rdbStore
} )
}
async getTaskList ( ) {
let predicates = new relationalStore . RdbPredicates ( this . tableName)
let result = await this . rdbStore. query ( predicates, [ 'ID' , 'NAME' , 'FINISHED' ] )
let tasks: TaskInfo[ ] = [ ]
while ( ! result. isAtLastRow) {
result. goToNextRow ( )
let id = result. getLong ( result. getColumnIndex ( 'ID' ) )
let name = result. getString ( result. getColumnIndex ( 'NAME' ) )
let finished = result. getLong ( result. getColumnIndex ( 'FINISHED' ) )
tasks. push ( { id, name, finished: ! ! finished} )
}
console . log ( 'testTag' , '查询到数据:' , JSON . stringify ( tasks) )
return tasks
}
addTask ( name: string ) : Promise < number > {
return this . rdbStore. insert ( this . tableName, { name, finished: false } )
}
updateTaskStatus ( id: number , finished: boolean ) {
let data = { finished}
let predicates = new relationalStore . RdbPredicates ( this . tableName)
predicates. equalTo ( 'ID' , id)
return this . rdbStore. update ( data, predicates)
}
deleteTaskById ( id: number ) {
let predicates = new relationalStore . RdbPredicates ( this . tableName)
predicates. equalTo ( 'ID' , id)
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 ( ) {
this . totalTask = this . tasks. length
this . finishTask = this . tasks. filter ( item => item. finished) . length
}
handleAddTask ( name: string ) {
TaskModel. addTask ( name)
. then ( id => {
console . log ( 'testTag' , '处理新增任务: ' , name)
this . tasks. push ( new TaskInfo ( id, name) )
this . handleTaskChange ( )
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)基础使用
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.' ) ;
} ) ;
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: [ '第一行' , '第二行' , '第三行' , '第四行' ] ,
}
}
}
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
}
}
} ;
async aboutToAppear ( ) {
let rm = getContext ( this ) . resourceManager;
let file = await rm. getMediaContent ( $r ( 'app.media.watchGT4' ) )
image. 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 {
idx: number = 100
pixel: PixelMap
async aboutToAppear ( ) {
let rm = getContext ( this ) . resourceManager;
let file = await rm. getMediaContent ( $r ( 'app.media.watchGT4' ) )
image. 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;
} ) . 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 = 0
progressMaxValue: number = 100
@ State state: DownloadState = DownloadState. NOT_BEGIN
filename: string = '圣诞星.mp4'
taskId: number = - 1
notificationId: number = 999
isSupport: boolean = false
async aboutToAppear ( ) {
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 ( ( ) => {
if ( 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 ( ) {
if ( ! this . isSupport) {
return
}
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 + '%'
}
}
}
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 ]
}
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 {
wantAgentInstance: WantAgent
async aboutToAppear ( ) {
this . isSupport = await notify. isSupportTemplate ( 'downloadTemplate' )
let wantInfo: wantAgent. WantAgentInfo = {
wants: [
{
bundleName: 'com.example.myapplication' ,
abilityName: 'EntryAbility' ,
}
] ,
requestCode: 0 ,
operationType: wantAgent. OperationType. START_ABILITY ,
wantAgentFlags: [ wantAgent. WantAgentFlags. CONSTANT_FLAG ]
}
this . wantAgentInstance = await wantAgent. getWantAgent ( wantInfo)
}
build ( ) {
····
}
open ( ) {
promptAction. showToast ( {
message: '功能未实现'
} )
}
publishDownloadNotification ( ) {
if ( ! this . isSupport) {
return
}
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 + '%'
}
}
}
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 )
}