作者是一名学生,在本学期选修课学习了鸿蒙系统这门课,为了综合练习本学期所学同时也为了完成本学期的期末作业,于是写了一个鸿蒙小Demo。

基本介绍
作用

可以查询手机号码属地并自动保存查询记录

主页面

『江鸟中原』鸿蒙小Demo_List

详情页

『江鸟中原』鸿蒙小Demo_Text_02

本次使用的开发工具是DevEco Studio,选择的开发模型是stage模型,所使用的开发语言是ArkTS。

代码结构

『江鸟中原』鸿蒙小Demo_HarmonyOS_03

代码示例
EntryAbility.ts
import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import data_preferences from '@ohos.data.preferences';
import http from '@ohos.net.http';

let httpRequest = http.createHttp();

interface ExpressState {
  time: number
  desc: string
}

interface ListExpress {
  number: string
  comName: string
  logo: string
  isExpressed: boolean
  list: ExpressState[]
}

export default class EntryAbility extends UIAbility {
  onCreate(want, launchParam) {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }

  onDestroy() {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    let preferences = null;
    try {
      data_preferences.getPreferences(this.context, 'ExpressList', function (err, val) {
        if (err) {
          console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
          return;
        }
        preferences = val;
        console.info("Succeeded in getting preferences.");
      })
      preferences.get('ExpressList', '[]').then((value) => {
        console.info("Succeeded in getting preferences value = " + value);
        let ExpressingList = [];
        let ExpressedList = [];
        (<ListExpress[]> JSON.parse(value)).forEach(element => {
          if (element.isExpressed) {
            ExpressedList.push(element);
          } else {
            httpRequest.request("https://qqlykm.cn/api/kd/?key=cCjvp4PwzIKpVwlv62wdaCJ86N&number=" + element, {
              header: {
                'Content-Type': 'application/json'
              }
            }).then((data) => {
              console.info('Result:' + data.result);
              const res = JSON.parse(<string> data.result);
              if (res.success) {
                element.comName = res.data.comName;
                element.logo = res.data.logo;
                element.list = res.data.list;
              }
            }).catch((err) => {
              console.info('error:' + JSON.stringify(err));
            });
            if (element.list[0].desc.match(/已签收/)) {
              element.isExpressed = true;
              ExpressedList.push(element);
            } else {
              ExpressingList.push(element);
            }
          }
        })

        AppStorage.SetOrCreate('ExpressingList', ExpressingList);
        AppStorage.SetOrCreate('ExpressedList', ExpressedList);
      }).catch((err) => {
        console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
      })
    } catch (err) {
      console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
    }

    windowStage.loadContent('pages/Index', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');

    const ExpressingList: ListExpress[] = AppStorage.SetAndLink('ExpressingList', []).get()
    const ExpressedList: ListExpress[] = AppStorage.SetAndLink('ExpressedList', []).get()

    const ExpressList: ListExpress[] = ExpressingList.concat(ExpressedList);

    let preferences = null;
    try {
      data_preferences.getPreferences(this.context, 'ExpressList', function (err, val) {
        if (err) {
          console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
          return;
        }
        preferences = val;
        console.info("Succeeded in getting preferences.");
      })
      preferences.put('ExpressList', JSON.stringify(ExpressList))
        .catch((err) => {
          console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
        })
    } catch (err) {
      console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
    }
  }

  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
Detail.ets
import router from '@ohos.router'

interface ListHistory {
  number: string
  area: string
  areacode: string
  zip: string
  company: string
  province: string
  city: string
}

@Entry
@Component
struct Detail {
  @State message: string = 'Hello World'
  @State Query: ListHistory = AppStorage.SetAndLink('Query', {
    "number": "",
    "area": "",
    "areacode": "",
    "zip": "",
    "company": "",
    "province": "",
    "city": ""
  }).get()

  build() {
    Row() {
      Column() {
        Text("<  手机号详情")
          .fontSize(18)
          .width('100%')
          .margin({ top: 10, bottom: 20, left: 20 })
          .textAlign(TextAlign.Start)
          .fontColor('#017CFE')
          .onClick(() => {
            router.back()
          })

        Row() {
          Image($r("app.media.app_icon"))
            .margin({ top: 10, bottom: 10, right: 10 })
            .height(54)
          Column() {
            Text(this.Query.number)
              .fontSize(16)
              .fontWeight(FontWeight.Bold)
            Text(this.Query.area)
              .fontSize(12)
            Text(this.Query.company)
              .fontSize(12)
              .maxLines(2)
            Text(this.Query.zip+" · "+this.Query.areacode)
              .fontSize(12)
          }
          .flexShrink(1)
          .justifyContent(FlexAlign.Center)
          .alignItems(HorizontalAlign.Start)
        }
        .borderRadius(10)
        .padding(10)
        .backgroundColor('#fff')
        .width('100%')
        .margin({ bottom: 10 })

        Text("- 详细信息 -")
          .fontSize(16)
          .margin({ bottom: 10 })

        Scroll() {
          List({ space: 10, initialIndex: 0 }) {
            ListItem() {
              Row() {
                Column() {
                  Text("省份")
                    .fontSize(16)
                    .fontWeight(FontWeight.Bold)
                  Text(this.Query.province)
                    .fontSize(24)
                    .margin({ top: 10 })
                }
                .flexShrink(1)
                .justifyContent(FlexAlign.Center)
                .alignItems(HorizontalAlign.Start)
              }
              .width('100%')
              .borderRadius(10)
              .padding(10)
              .backgroundColor('#fff')
            }
            .width('100%')
            ListItem() {
              Row() {
                Column() {
                  Text("城市")
                    .fontSize(16)
                    .fontWeight(FontWeight.Bold)
                  Text(this.Query.city)
                    .fontSize(24)
                    .margin({ top: 10 })
                }
                .flexShrink(1)
                .justifyContent(FlexAlign.Center)
                .alignItems(HorizontalAlign.Start)
              }
              .width('100%')
              .borderRadius(10)
              .padding(10)
              .backgroundColor('#fff')
            }
            .width('100%')
            ListItem() {
              Row() {
                Column() {
                  Text("运营商")
                    .fontSize(16)
                    .fontWeight(FontWeight.Bold)
                  Text(this.Query.company)
                    .fontSize(24)
                    .margin({ top: 10 })
                }
                .flexShrink(1)
                .justifyContent(FlexAlign.Center)
                .alignItems(HorizontalAlign.Start)
              }
              .width('100%')
              .borderRadius(10)
              .padding(10)
              .backgroundColor('#fff')
            }
            .width('100%')
            ListItem() {
              Row() {
                Column() {
                  Text("地区编码")
                    .fontSize(16)
                    .fontWeight(FontWeight.Bold)
                  Text(this.Query.areacode)
                    .fontSize(24)
                    .margin({ top: 10 })
                }
                .flexShrink(1)
                .justifyContent(FlexAlign.Center)
                .alignItems(HorizontalAlign.Start)
              }
              .width('100%')
              .borderRadius(10)
              .padding(10)
              .backgroundColor('#fff')
            }
            .width('100%')
            ListItem() {
              Row() {
                Column() {
                  Text("邮政编码")
                    .fontSize(16)
                    .fontWeight(FontWeight.Bold)
                  Text(this.Query.zip)
                    .fontSize(24)
                    .margin({ top: 10 })
                }
                .flexShrink(1)
                .justifyContent(FlexAlign.Center)
                .alignItems(HorizontalAlign.Start)
              }
              .width('100%')
              .borderRadius(10)
              .padding(10)
              .backgroundColor('#fff')
            }
            .width('100%')
          }
        }
        .flexShrink(1)
      }
      .height('100%')
      .padding(10)
    }
    .height('100%')
    .backgroundColor('#eee')
  }
}
Index.ets
import http from '@ohos.net.http';
import router from '@ohos.router'

let httpRequest = http.createHttp();

interface ListHistory {
  number: string
  area: string
  areacode: string
  zip: string
  company: string
  province: string
  city: string
}

@Entry
@Component
struct Index {
  @State QueryHistory: ListHistory[] = AppStorage.SetAndLink('QueryHistory', []).get()

  build() {
    Column() {
      Search({ placeholder: '输入电话号码' })
        .searchButton('查询')
        .height(40)
        .margin(20)
        .onSubmit((value: string) => {
          httpRequest.request("https://apis.juhe.cn/mobile/get?dtype=&key=68b22126dba600fc2d240a8ef5a43270&phone=" + value, {
            header: {
              'Content-Type': 'application/json'
            }
          }).then((data) => {
            console.info('Result:' + data.result);
            const res = JSON.parse(<string> data.result);
            let item: ListHistory = {
              number: value,
              area: res.result.province + " · " + res.result.city,
              areacode: res.result.areacode,
              zip: res.result.zip,
              company: res.result.company,
              province: res.result.province,
              city: res.result.city
            }
            console.log(JSON.stringify(item))
            this.QueryHistory.push(item);
            AppStorage.Set('QueryHistory', this.QueryHistory);
          }).catch((err) => {
            console.info('error:' + JSON.stringify(err));
          });
        })
      Tabs({ barPosition: BarPosition.Start }) {
        TabContent() {
          Column() {
            List({ space: 10, initialIndex: 0 }) {
              ForEach(this.QueryHistory, (item, index) => {
                ListItem() {
                  Row() {
                    Image($r("app.media.app_icon"))
                      .margin({ top: 10, bottom: 10, right: 10 })
                      .height(54)
                    Column() {
                      Text(item.number)
                        .fontSize(16)
                        .fontWeight(FontWeight.Bold)
                      Text(item.area)
                        .fontSize(12)
                      Text(item.company)
                        .fontSize(12)
                        .maxLines(2)
                      Text(item.zip + " · " + item.areacode)
                        .fontSize(12)
                    }
                    .flexShrink(1)
                    .justifyContent(FlexAlign.Center)
                    .alignItems(HorizontalAlign.Start)
                  }
                  .width('100%')
                  .borderRadius(10)
                  .padding(10)
                  .backgroundColor('#fff')
                }
                .width('100%')
                .onClick(() => {
                  AppStorage.SetOrCreate('Query', item);
                  router.pushUrl({
                    url: 'pages/Detail'
                  })
                })
              }, item => item)
            }
            .padding(10)
          }.width('100%').height('100%')
        }.tabBar(`查询历史`)
      }
      .barHeight(48)
      .backgroundColor('#F1F3F5')
      .flexShrink(1)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Start)
  }
}
总结

上述就是我使用本学期以及参考网上资料写出的鸿蒙Demo,今后也会不断学习鸿蒙的相关知识增进自身实力。