• HarmonyOS应用开发入门(五)


    一、网络连接

    网络管理模块主要提供以下功能:

    • HTTP数据请求:通过HTTP发起一个数据请求。
    • WebSocket连接:使用WebSocket建立服务器与客户端的双向连接。
    • Socket连接:通过Socket进行数据传输。

    1、Http请求数据

    (1)导入http模块:

     import http from '@ohos.net.http';

    (2)使用http模块发送请求,处理响应:

    1. // 创建一个http的请求对象,不可复用
    2. let httpRequest = http.createHttp()
    3. // 发起网络请求
    4. httpRequest.request(
    5. 'http://localhost:3000/users', // 请求URL路径
    6. {
    7. // 请求选项 HttpRequestOptions
    8. method: http.RequestMethod.GET,
    9. extraData: {'param1': 'value1'}
    10. }
    11. ) // Promise:存放未来会完成的结果
    12. // 处理响应结果
    13. .then((resp: http.HttpResponse) => {
    14. if (resp.responseCode === 200){
    15. // 请求成功
    16. }
    17. })
    18. .catch((err: Error) => {
    19. // 请求失败
    20. })
    HttpRequestOptions
    名称类型描述
    methodRequestMethod请求方式,GET、POST、PUT、DELETE等
    extraDatastring|Object请求参数
    headerObject请求头字段
    connectTimeoutnumber连接超时时间,单位毫秒,默认60000ms
    readTimeoutnumber读取超时间,单位毫秒,默认60000ms
    HttpResponse
    名称类型描述
    responseCodeResponseCode响应状态码
    headerObject响应头
    cookiesstring响应返回的cookies
    resultstring|Object响应体,默认是JSON字符串
    resultTypeHttpDataType返回值类型

    npm install:安装服务端依赖;

    npm start:启动服务端;

    2、第三方库axios

    第三方库学习地址:OpenHarmony三方库中心仓

    (1)下载和安装ohpm

    1. # windows环境
    2. init.bat
    3. # LinuxMac环境
    4. ./init.sh
    • 将ohpm配置到环境变量;
    1. # windows环境,直接在我的电脑配置即可
    2. #LinuxMac环境,其中OHPM的路径请替换为ohpm的安装路径
    3. export OHPM_HOME=/xx/ohpm
    4. export PATH=${OHPM_HOME}/bin:${PATH}
    • 安装完成之后,执行如下命令,终端输出为版本号,则表示安装成功。
    ohpm -v

    (2)下载和安装axios

    • 下载axios:
    1. # 进入项目目录,然后输入下面命令
    2. ohpm install @ohos/axios
    •  开放网络权限:在模块的module.json5文件中配置网络权限。

    安装成功:

    (3)使用axios

    • 导入axios:
    1. // 导入axios模块
    2. import axios from '@ohos/axios'
    • 发送请求并处理响应:
    1. axios.get( // 请求方式
    2. 'url', // 请求路径
    3. {
    4. params:{ 'param1':'value1' }, // 请求选项
    5. data:{ 'param1':'value1' }
    6. }
    7. )
    8. .then(response => { // 响应结果,AxiosResponse
    9. if(response.status !== 200){
    10. console.log('查询失败')
    11. }
    12. console.log('查询成功')
    13. })
    14. .catch(error => {
    15. console.log('查询失败',JSON.stringify(error))
    16. })
    17. }
    AxiosResponse
    名称类型描述
    statusnumber响应状态码
    headerObject响应头
    dataany服务端返回的响应体

    二、数据库

    1、用户首选项

    用户首选项(Preferences)为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。属于非关系型数据库:不保证遵循ACID(Atomic、Consistence、Isolation、Durability),不采用关系模型组织数据,数据间无关系。

    • Key为string类型,非空,字符长度不超过80个字节;
    • Value为string类型时,可以为空,字符长度不超过8192字节;
    • Preferences实例会加载到内存中,建议数据不超过1万条,并及时清理不再使用的实例,减少内存开销;

     用户首选项运作机制:

    (1)导入首选项模块:

    import dataPreference from '@ohos.data.preferences'

    (2)获取首选项实例,读取指定文件:

    1. dataPreference.getPreferences(this.context, 'MyAppPreference')
    2. .then(preferences => {
    3. // 获取成功
    4. })
    5. .catch(reason => {
    6. // 获取失败
    7. })

     (3)数据操作:

    • 写入数据,如果已经存在则会覆盖,可利用.has()判断是否存在:
    1. preferences.put('key',val)
    2. .then(() => preferences.flush()) // 刷到磁盘
    3. .catch(reason => {}) // 处理异常
    • 删除数据:
    1. preferences.delete('key')
    2. .then(() => {})
    3. .catch(reason => {})
    • 查询数据
    1. preferences.get('key','defaultValue')
    2. .then(value => console.log('查询成功'))
    3. .catch(reason => console.log('查询失败'))

    2、关系型数据库

    关系型数据库(RDB)基于SQLite组件提供的本地数据库,适用于存储包含复杂关系数据的场景。

    (1)初始化数据库

    • 导入关系型数据库模块:
    import relationalStore from '@ohos.data.relationalStore';
    • 初始化数据库表:
    1. // rdb配置
    2. const config = {
    3. name: 'MyApplication.db', // 数据库文件名
    4. securityLevel: relationalStore.SecurityLevel.S1 // 数据库安全级别
    5. }
    6. // 初始化表的SQL
    7. const sql = `CREATE TABLE IF NOT EXISTS TASK(
    8. ID INTEGER PRIMARY KEY...)`
    9. // 获取rdb
    10. relationalStore.getRdbStore(this.context,config,(err,rdbStore) => {
    11. // 执行SQL,后续的所有增删改查都使用rdbStore对象
    12. rdbStore.executeSql(sql)
    13. })

    (2)增、删、改数据

    • 新增数据:
    1. // 准备数据
    2. let task = {id: 1,name:'任务'}
    3. // 新增
    4. this.rdbStore.insert(this.tableName,task)
    • 修改:
    1. // 要更新的数据
    2. let task = {'finished': true};
    3. // 查询条件,RdbPredicates就是条件谓词
    4. let predicates = new relationalStore.RdbPredicates(this.tableName)
    5. predicates.equalTo('ID',id)
    6. // 执行更新
    7. this.rdbStore.updata(task, predicates)
    • 删除:
    1. // 查询条件,RdbPredicates就是条件谓词
    2. let predicates = new relationalStore.RdbPredicates(this.tableName)
    3. predicates.equalTo('ID',id)
    4. // 执行删除
    5. this.rdbStore.delete(predicates)

    (3)查询数据

    • 查询数据:
    1. // 查询条件
    2. let predicates = new relationalStore.RdbPredicates(this.tableName)
    3. // 执行查询
    4. let result = await this.rdbStore.query(predicates,['ID','NAME','FINISHED'])
    • 解析结果:
    1. // 准备数组保存结果
    2. let tasks: any[] = []
    3. // 循环遍历结果集,判断结果是否遍历到最后一行
    4. while (!result.isAtLastRow){
    5. // 指针移动到下一行数据
    6. result.goToNextRow()
    7. // 根据字段名获取字段index,从而获取字段值
    8. let id = result.getLong(result.getColumnIndex('ID'));
    9. let name = result.getString(result.getColumnIndex('NAME'));
    10. tasks.push({id,name})
    11. }

    三、通知

    1、基础通知

    应用可以通过通知接口发送通知消息,提醒用户关注应用中的变化。用户可以在通知栏查看和操作通知内容。

    (1)导入notification模块:

    import notification from '@ohos.notification';

    (2)发布通知:

    1. // 构建通知请求
    2. let request: notificationManager.NotificationRequest = {
    3. id: 10,
    4. content: {
    5. // 通知内容:...
    6. },
    7. deliverTime: new Data().getTime(), // 显示时间
    8. showDeliveryTime: true,
    9. groupName: 'xxx', // 分组名称
    10. slotType: notify.SlotType.SOCIAL_COMMUNICATION,
    11. }
    12. // 发布通知
    13. notificationManager.publish(request)
    14. .then(() => console.log('发送通知成功'))
    15. .catch(reason => console.log('发送通知失败',JSON.stringify(reason)))

    SlotType枚举类型设置通知的类型, SOCIAL_COMMUNICATION有状态栏图标,有提示音,有横幅,SERVICE_INFORMATION没有横幅,CONTENT_INFORMATION只有状态栏图标,OTHER_TYPES什么都没有。

    内容类型(contentType):

    类型描述
    NOTIFICATION_CONTENT_BASIC_TEXT普通文本类型
    NOTIFICATION_CONTENT_LONG_TEXT长文本类型
    NOTIFICATION_CONTENT_MULTILINE多行文本类型
    NOTIFICATION_CONTENT_PICTURE图片类型

    对于content中的属性设置以NOTIFICATION_CONTENT_BASIC_TEXT为例:

    1. content: {
    2. contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    3. normal: {
    4. title: '通知标题',
    5. text: '通知内容详情',
    6. additionalText: '通知附加内容'
    7. }
    8. }

    类似的,对于NOTIFICATION_CONTENT_LONG_TEXT,第二个属性参数为longText,其在normal的基础上加入了“longText”(通知中的长文本)、“briefText”(通知概要和总结)、“expandedTitle”(通知展开时的标题);对于NOTIFICATION_CONTENT_MULTILINE,第二个属性参数为multiline,其在normal的基础上加入了“briefText”(通知概要和总结)、“longTitle”(展开时的标题)、“lines”([多行]);对于NOTIFICATION_CONTENT_PICTURE,第二个属性参数为picture,,其在normal的基础上加入了“additionalText”(通知附加内容)、“briefText”(通知概要和总结)、“expandedTitle”(通知展开时的标题)、以及“picture”(picture: this.pixel)。

    对于图片的获取:

    1. async aboutToAppear(){
    2. // 获取资源管理器
    3. let rm = getContext(this).resourceManager;
    4. // 读取图片
    5. let file = await rm.getMediaContent($r('app.media.icon'))
    6. // 创建PixelMap
    7. image.createImageSource(file.buffer).createPixelMap()
    8. .then(value => this.pixel = value)
    9. .catch(reason => console.log('testTag','加载图片异常',JSON.stringify(reason)))
    10. }

    (3)取消通知:

    1. // 取消指定id的通知
    2. notificationManager.cancel(id)
    3. // 取消当前应用所以通知
    4. notificationManager.cancelAll()

    2、进度条通知

    展示一个动态的进度条,主要应用于文件下载、事务处理进度显示。

    (1)判断当前系统是否支持进度条模板:

    1. this.isSupport = await notificationManager.isSupportTemplate('downloadTemplate')
    2. if(!this.isSupport){
    3. return
    4. }

    (2)定义通知请求:

    1. // 通知模板
    2. let template = {
    3. name: 'downloadTemplate' // 模板名称,必须是downloadTemplate
    4. data:{
    5. progressValue: this.progressValue // 进度条当前进度
    6. progressMaxValue: 100 // 进度条最大值
    7. }
    8. }
    9. // 通知请求
    10. let request: notificationManager.NotificationRequest = {
    11. id: 999,
    12. template: template,
    13. content: {
    14. contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    15. normal: {
    16. title: this.filename + ':' + this.state,
    17. text: '',
    18. additionalText: `${this.progressValue}%`
    19. }
    20. }
    21. }

    3、通知意图

    当发布通知时,如果期望用户可以通过点击通知栏拉起目标应用组件或发布公共事件,可以通过Ability Kit申请WantAgent封装至通知消息中。

    1. // 意图行为信息
    2. let wantInfo = {
    3. wants: [
    4. {
    5. deviceId: '',
    6. bundleName: 'com.example.myapplication',
    7. abilityName: 'EntryAbility',
    8. action: '',
    9. entities: [],
    10. }
    11. ],
    12. operationType: wantAgent.OperationType.START_ABILITY,
    13. requestCode: 0,
    14. wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
    15. };
    16. // 创建wantAgent实例
    17. let wantAgentInstance = await wantAgent.getWantAgent(wantInfo)
    18. // 通知请求
    19. let request: notify.NotificationRequest = {
    20. id: 999,
    21. template: template,
    22. wantAgent: this.wantAgentInstance, // 设置通知意图
    23. content: {
    24. // ...
    25. }
    26. }
  • 相关阅读:
    正则匹配语法学习
    数据链路层具体协议
    Arcgis提取点数据经纬度
    计算机毕设 基于生成对抗网络的照片上色动态算法设计与实现 - 深度学习 opencv python
    “千方百计“测病毒
    鸿蒙开发接口定制管理:【@ohos.enterpriseDeviceManager (企业设备管理)】
    Python电梯楼层数字识别
    设计模式之门面模式
    47个“企业数字化转型”常见术语合集,看完秒懂~
    前端提高代码质量-提升代码的可维护性
  • 原文地址:https://blog.csdn.net/weixin_52554463/article/details/140425044