2024鸿蒙样题需要掌握的知识点

一、读取json格式文件为对象或数组,显示相应字段

1、创建json文件的参数一致的类

2、导入类、导入json文件

3、循环渲染

javascript 复制代码
import router from '@ohos.router'
//导入即对象
import books from 'resources/rawfile/book1.json'
import { Book } from '../model/Book'

@Entry
@Component
struct Detail {

  build() {
    Column() {
      //展示所有的图书-->读取book文件
      ForEach(books.book, (item: Book) => {
        Text(item.bookName)
      })
    }
    .height('100%')
    .width('100%')
  }
}

二、推送普通文本类型通知

++注意++ :测试的时候需要在模拟器中打开通知权限

javascript 复制代码
//基础文本通知
import { notificationManager } from '@kit.NotificationKit';
// 描述通知的请求
let notificationRequest: notificationManager.NotificationRequest = {
  //id为通知的唯一标识,用于通讯的通知与取消
  id: 100,
  content: {
    //notificationContentType定义通知的类型
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    //normal定义普通文本类型通知的内容
    normal: {
      //title定义通知内容标题
      title: `通知内容标题`,
      //title定义通知内容详情
      text: '通知内容详情'
    }
  }
}
// 发送通知
notificationManager.publish(notificationRequest).then(()=>{
  console.info('publish success')
})
  .catch((err: Error) => {
  console.error(`publish failed,message is ${err}`);
});

简化版

javascript 复制代码
    notificationManager.publish({
      id: 1,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '图书馆的通知',
          text: '这里是图书馆的通知'
        }
      }
    })

三、打开和关闭子窗口;鼠标拖拽子窗口;在子窗口页面中显示轮播图;点击轮播图,跳转到某图书详细信息页面。

1、打开和关闭窗口

①、首先定义一个类

javascript 复制代码
import { window } from '@kit.ArkUI'

class MyWindows {
  WindowStage: window.WindowStage | null = null
  SubWindow: window.Window | null = null

  //打开小窗
  async show() {
    if (this.WindowStage == null) {
      console.log('testTag', '发生错误,无法打开小窗')
    } else {
      this.SubWindow = await this.WindowStage.createSubWindow('xiejiarui')
      //窗口位置
      this.SubWindow.moveWindowTo(440, 550)
      //窗口大小
      this.SubWindow.resize(800, 1500)
    }
    this.SubWindow?.setUIContent("pages/Small_window", () => {
      (this.SubWindow as window.Window).showWindow()
    })
  }

  //关闭小窗
  close() {
    this
      .SubWindow?.destroyWindow((err) => {
      if (err) {
        console.log("testTag", '发生错误 无法关闭小窗')
      } else {
        console.log('testTag', '成功关闭小窗')
      }
    })
  }
}

export default new MyWindows()

②、在EntryAbility中初始化

复制代码
export default class EntryAbility extends UIAbility {
  async onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
    windowStage.loadContent('pages/Index', (err) => {
      ……
    });

    //小窗
    let windowsClass = await windowStage.getMainWindow()
    let name: Array<"status" | "navigation"> = []
    windowsClass.setWindowSystemBarEnable(name)
    MyWindows.WindowStage = windowStage
  }

③、在需要打开小窗的地方调用

复制代码
//注意:需要导入MyWindows的ets文件
Button('点击弹出小窗')
  .onClick(() => {
  MyWindows.ShowSubWindows()
})

④、在需要关闭小窗的地方调用

复制代码
//注意:需要导入MyWindows的ets文件
Button('点击关闭窗口')
  .onClick(()=>{
    MyWindows.destroySubWindow()
  })

四、使用视频组件显示视频文件。

复制代码
//视频控制器
controller: VideoController = new VideoController()
复制代码
Video({ src: this.book.videoPath, controller: this.controller })
  .width('85%')
  .height(180)
  .autoPlay(true)

五、用户首选项或关系型数据库进行数据持久化存储。

1、通过用户首选项实现数据持久化

⑴封装用户首选项工具类

javascript 复制代码
import { preferences } from "@kit.ArkData"

class PreferencesUtil {
  //创建一个变量来保存preferences的实例
  private pref: preferences.Preferences | null = null

  //获取Preferences实例
  createPreferences(context: Context) {
    //获取preferences的实例【第一个参数是context(应用场下文),第二个参数是实例的名称】
    preferences.getPreferences(context, 'shop_preferences')
      .then((object) => {
        //成功时会返回preferences实例
        this.pref = object
        console.log('testTag', '成功获取preferences实例')
      })
      .catch(() => {
        console.log('testTag', '获取preferences实例失败')
      })
  }

  //将数据写入preferences实例
  async writePreferenceValue(key: string, value: preferences.ValueType) {
    //判断一下preferences是否实例化
    if (!this.pref) {
      return
    }
    try { //实例化后,调用put方法来写入数据【第一个值传入要写入的string类型的Key,第二个值是要写入的数据】
      await this.pref.put(key, value)
      //通过flash方法将preferences实例持久化
      await this.pref.flush()
      console.log('testTag,写入数据成功')
    } catch (e) {
      console.log('testTag,写入数据失败')
    }
  }

  //读数据的操作
  //获取键对应的值
  async readPreferenceValue<T extends preferences.ValueType>(key: string, defaultValue: T) {
    //判断一下preferences是否实例化
    if (!this.pref) {
      console.log('testTag, preferences未实例化,返回默认值')
      return defaultValue // 未实例化时返回默认值
    }
    try { //实例化后,调用get方法获取数据【第一个值传入要获取的string类型的Key,第二个值表示默认值】
      let value = await this.pref.get(key, defaultValue) as T
      console.log('testTag,读取数据成功')
      return value
    } catch (e) {
      console.log('testTag,写入数据失败')
      return defaultValue // 出错时返回默认值
    }
  }
}

export default new PreferencesUtil()

⑵初始化用户首选项

复制代码
import PreferencesUtil from '../utils/PreferencesUtil'

const DOMAIN = 0x0000;

export default class EntryAbility extends UIAbility {
  async onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
     …… ……
    //实例化preferences
    PreferencesUtil.createPreferences(this.context)
  }
}

⑶使用用户首选项

复制代码
Button('记录数据')
  .onClick(()=>{
    PreferencesUtil.writePreferenceValue("姓名","RAY")
  })
Button('读取数据')
  .onClick(async ()=>{
    this.message=await PreferencesUtil.readPreferenceValue("姓名","name")
  })
Text(`数据为:${this.message}`)

2、通过关系型数据库实现数据库持久化


六、在页面跳转时进行传值

1、字符串类型

//传值

复制代码
router.pushUrl({
  url:'pages/Detail',
  params:{
    libraryName:'图书馆'
  }
})

//接收(注意类型)

复制代码
const Params: string = router.getParams()as string
const libraryName:String=Params['libraryName']

2、对象类型

//传值

复制代码
router.pushUrl({
  url: 'pages/Detail',
  params: {
    name : '',
    book : ''
  }
})

//接收

//Entry外定义类

复制代码
class library {
  name: String = ''
  book: String = ''
}

//build前接收值

复制代码
const Params: library = router.getParams()as library
const name:String=Params.name
const book:String=Params.book

七、使用华为云,创建云函数;并根据云函数返回的接口地址,使用http进行网络数据获取。

1、创建云函数

然后点击刚刚创建的触发器,点击修改,按需修改(Path等),点击修改成功

然后找到刚刚的API,在总览中复制API URL

2、调用云函数

复制代码
//注意:需要导入http包(import http from '@ohos.net.http')
let data=await http.createHttp().request('刚刚复制的API URL')
console.log("testTag","调用华为云的云函数,返回的值是",`${data.result}`)

八、打开手机拨号界面。

复制代码
//调用查询能力接口
let isSupport = call.hasVoiceCapability()
//如果有能力拨打电话
if (isSupport) {
  //向10086拨打电话
  call.makeCall("10086",(err)=>{
    if (err) {
      //拨打电话的时候发生错误,打印日志
      console.log('testTag',"拨打电话失败")
    }else {
      //拨打电话成功,打印日志
      console.log('testTag',"拨打电话成功")
    }
  })
}

简化版

复制代码
call.makeCall("10086")
相关推荐
奶糖不太甜3 小时前
鸿蒙UI布局不兼容解决方案笔记
harmonyos
小小小小小星3 小时前
鸿蒙开发调试技巧整理
harmonyos
HarderCoder3 小时前
重学仓颉-2基础编程概念详解
harmonyos
御承扬7 小时前
HarmonyOS NEXT系列之元服务框架ASCF
华为·harmonyos
HarderCoder7 小时前
重学仓颉-1从零开始学习现代编程语言
harmonyos
li理10 小时前
鸿蒙应用开发深度解析:从基础列表到瀑布流,全面掌握界面布局艺术
前端·前端框架·harmonyos
博睿谷IT99_12 小时前
OSPF 的工作过程、Router ID 机制、报文结构
开发语言·网络·华为·智能路由器·网络工程师·华为认证·数据通信
万少1 天前
可可图片编辑 HarmonyOS(2) 选择图片和保存到图库
harmonyos
小小小小小星1 天前
鸿蒙开发性能优化实战指南:从工具到代码全解析
性能优化·harmonyos