鸿蒙智能快递柜取件助手开发指南 原创

进修的泡芙
发布于 2025-6-20 13:26
浏览
0收藏

鸿蒙智能快递柜取件助手开发指南(安全版)

一、系统架构设计

基于HarmonyOS的智能快递柜取件助手,利用短信识别和分布式能力实现安全可靠的快递管理:
短信识别:安全解析短信中的取件信息

数据加密:所有传输数据采用端到端加密

权限控制:严格遵循最小权限原则

隐私保护:用户数据本地化处理

!https://example.com/harmony-parcel-safe-arch.png

二、核心代码实现
安全短信解析服务

// SecureSmsService.ets
import sms from ‘@ohos.telephony.sms’;
import cipher from ‘@ohos.security.cipher’;

class SecureSmsService {
private static instance: SecureSmsService = null;
private listeners: SmsListener[] = [];
private crypto: cipher.Crypto;

private constructor() {
this.initCrypto();
this.initSmsObserver();
public static getInstance(): SecureSmsService {

if (!SecureSmsService.instance) {
  SecureSmsService.instance = new SecureSmsService();

return SecureSmsService.instance;

private initCrypto(): void {

this.crypto = cipher.createCrypto('AES256-GCM');

private initSmsObserver(): void {

sms.on('smsReceive', (data) => {
  this.processSmsData(data.message);
});

private processSmsData(message: string): void {

// 使用安全正则表达式匹配
const patterns = [
  /验证码:(\d{4,6})[\s,,]+位置:(.+?)快递柜/i,
  /【(.+?)】您的取件码是(\d{4,6})[\s,,]+请到(.+?)取件/i
];

let extractedCode = '';
let extractedLocation = '';
let extractedCarrier = '';

patterns.forEach(pattern => {
  const match = message.match(pattern);
  if (match && match.length >= 3) {
    extractedCode = match[1];
    extractedLocation = match[2];
    if (match.length > 3) {
      extractedCarrier = match[1];

}

});

if (extractedCode && extractedLocation) {
  const parcelData = {
    receiveTime: Date.now(),
    verificationCode: extractedCode,
    location: extractedLocation,
    carrier: extractedCarrier || '未知快递',
    status: '待取件'
  };
  
  // 加密敏感数据
  const encryptedData = this.encryptParcelData(parcelData);
  this.notifyListeners(encryptedData);

}

private encryptParcelData(data: object): string {
const jsonStr = JSON.stringify(data);
return this.crypto.encrypt(jsonStr);
private notifyListeners(encryptedData: string): void {

this.listeners.forEach(listener => {
  listener.onSmsReceived(encryptedData);
});

public addListener(listener: SmsListener): void {

if (!this.listeners.includes(listener)) {
  this.listeners.push(listener);

}

public removeListener(listener: SmsListener): void {
this.listeners = this.listeners.filter(l => l !== listener);
}

interface SmsListener {
onSmsReceived(encryptedData: string): void;
export const secureSmsService = SecureSmsService.getInstance();

安全数据同步服务

// SecureSyncService.ets
import distributedData from ‘@ohos.distributedData’;
import cipher from ‘@ohos.security.cipher’;

class SecureSyncService {
private static instance: SecureSyncService = null;
private dataManager: distributedData.DataManager;
private crypto: cipher.Crypto;
private listeners: SyncListener[] = [];

private constructor() {
this.initDataManager();
this.initCrypto();
public static getInstance(): SecureSyncService {

if (!SecureSyncService.instance) {
  SecureSyncService.instance = new SecureSyncService();

return SecureSyncService.instance;

private initDataManager(): void {

this.dataManager = distributedData.createDataManager({
  bundleName: 'com.example.parcel',
  area: distributedData.Area.GLOBAL,
  isEncrypted: true
});

this.dataManager.registerDataListener('parcel_sync', (data) => {
  this.handleSyncData(data);
});

private initCrypto(): void {

this.crypto = cipher.createCrypto('AES256-GCM');

public syncParcelInfo(info: object): void {

const encrypted = this.crypto.encrypt(JSON.stringify(info));
this.dataManager.syncData('parcel_sync', {
  type: 'parcel_info',
  data: encrypted,
  timestamp: Date.now()
});

private handleSyncData(data: any): void {

if (!data || !data.data) return;

try {
  const decrypted = this.crypto.decrypt(data.data);
  const parcelInfo = JSON.parse(decrypted);
  
  this.listeners.forEach(listener => {
    switch (data.type) {
      case 'parcel_info':
        listener.onParcelInfo(parcelInfo);
        break;

});

catch (err) {

  console.error('处理同步数据失败:', JSON.stringify(err));

}

public addListener(listener: SyncListener): void {
if (!this.listeners.includes(listener)) {
this.listeners.push(listener);
}

public removeListener(listener: SyncListener): void {
this.listeners = this.listeners.filter(l => l !== listener);
}

interface SyncListener {
onParcelInfo(info: object): void;
export const secureSyncService = SecureSyncService.getInstance();

主界面实现(安全版)

// SafeMainScreen.ets
import { secureSmsService } from ‘./SecureSmsService’;
import { secureSyncService } from ‘./SecureSyncService’;
import cipher from ‘@ohos.security.cipher’;

@Component
export struct SafeMainScreen {
@State parcelList: Array<object> = [];
@State connectedDevices: string[] = [];
@State activeTab: ‘all’ | ‘pending’ = ‘all’;

private crypto: cipher.Crypto;

aboutToAppear() {
this.crypto = cipher.createCrypto(‘AES256-GCM’);
this.setupListeners();
private setupListeners(): void {

secureSmsService.addListener({
  onSmsReceived: (encryptedData) => {
    this.handleNewParcel(encryptedData);

});

secureSyncService.addListener({
  onParcelInfo: (info) => {
    this.addParcel(info);

});

private handleNewParcel(encryptedData: string): void {

try {
  const decrypted = this.crypto.decrypt(encryptedData);
  const parcelInfo = JSON.parse(decrypted);
  this.addParcel(parcelInfo);
  secureSyncService.syncParcelInfo(parcelInfo);

catch (err) {

  console.error('解析快递数据失败:', JSON.stringify(err));

}

private addParcel(info: object): void {
if (!this.parcelList.some(item =>
item.verificationCode === info.verificationCode &&
item.location === info.location)) {
this.parcelList = [info, …this.parcelList];
}

build() {
Column() {
// 标题栏
Row() {
Text(‘安全快递助手’)
.fontSize(24)
.fontWeight(FontWeight.Bold)
.layoutWeight(1)

    Button('设备')
      .width(80)
      .onClick(() => {
        this.showDeviceDialog();
      })

.padding(10)

  // 内容区域
  if (this.parcelList.length === 0) {
    this.buildEmptyView()

else {

    this.buildParcelListView()

}

.width('100%')
.height('100%')

@Builder

private buildEmptyView() {
Column() {
Image($r(‘app.media.ic_empty_box’))
.width(120)
.height(120)
.margin({ bottom: 20 })

  Text('暂无快递记录')
    .fontSize(16)
    .fontColor('#666666')

.width(‘100%’)

.height('100%')
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)

@Builder

private buildParcelListView() {
List() {
ForEach(this.parcelList, (item) => {
ListItem() {
Column() {
Row() {
Text(item.carrier || ‘快递服务’)
.fontSize(18)
.fontWeight(FontWeight.Bold)
.layoutWeight(1)

          Text(this.formatTime(item.receiveTime))
            .fontSize(12)
            .fontColor('#999999')

.margin({ bottom: 8 })

        Row() {
          Text(取件码: ${item.verificationCode})
            .fontSize(16)
            .layoutWeight(1)
          
          if (item.status === '待取件') {
            Button('开柜')
              .width(80)
              .onClick(() => {
                this.openLocker(item);
              })

else {

            Text(item.status)
              .fontColor(item.status === '已取件' ? '#4CAF50' : '#F44336')

}

        Text(item.location)
          .fontSize(14)
          .fontColor('#666666')
          .margin({ top: 8 })

.padding(15)

      .width('100%')

.borderRadius(8)

    .backgroundColor(Color.White)
    .margin({ top: 10, bottom: 10, left: 15, right: 15 })
  })

.width(‘100%’)

.height('100%')

private openLocker(parcelInfo: object): void {

prompt.showDialog({
  title: '安全验证',
  message: 确认要打开 ${parcelInfo.location} 的快递柜吗?,
  buttons: [

text: ‘取消’,

      color: '#666666'
    },

text: ‘确认’,

      color: '#2196F3',
      action: () => {
        this.updateParcelStatus(parcelInfo, '已取件');
        prompt.showToast({ message: '操作成功' });

}

});

private updateParcelStatus(parcelInfo: object, status: string): void {

const updated = {...parcelInfo, status};
this.parcelList = this.parcelList.map(item => 
  item.verificationCode === parcelInfo.verificationCode &&
  item.location === parcelInfo.location ? updated : item
);

secureSyncService.syncParcelInfo(updated);

private formatTime(timestamp: number): string {

const date = new Date(timestamp);
return {date.getMonth()+1}月{date.getDate()}日 {date.getHours()}:{date.getMinutes().toString().padStart(2, '0')};

private showDeviceDialog(): void {

// 设备选择对话框实现

}

三、安全配置
权限配置

// module.json5
“module”: {

"requestPermissions": [

“name”: “ohos.permission.RECEIVE_SMS”,

    "reason": "安全读取短信获取取件信息",
    "usedScene": {
      "ability": ["MainAbility"],
      "when": "always"

},

“name”: “ohos.permission.DISTRIBUTED_DATASYNC”,

    "reason": "加密同步快递数据",
    "usedScene": {
      "ability": ["MainAbility"],
      "when": "always"

},

“name”: “ohos.permission.ACCESS_DISTRIBUTED_DEVICE_MANAGER”,

    "reason": "安全设备发现和连接",
    "usedScene": {
      "ability": ["DeviceAbility"],
      "when": "always"

},

“name”: “ohos.permission.USE_CRYPTO”,

    "reason": "数据加密处理",
    "usedScene": {
      "ability": ["MainAbility"],
      "when": "always"

}

],
"abilities": [

“name”: “MainAbility”,

    "type": "page",
    "visible": true,
    "permissions": [
      "ohos.permission.RECEIVE_SMS",
      "ohos.permission.DISTRIBUTED_DATASYNC",
      "ohos.permission.USE_CRYPTO"

},

“name”: “DeviceAbility”,

    "type": "page",
    "visible": true,
    "permissions": [
      "ohos.permission.ACCESS_DISTRIBUTED_DEVICE_MANAGER"

}

}

安全资源文件

// resources/base/media/media.json
“media”: [

“name”: “ic_empty_box”,

  "type": "svg",
  "src": "media/empty_box.svg"
},

“name”: “ic_lock”,

  "type": "svg",
  "src": "media/lock.svg"
},

“name”: “ic_shield”,

  "type": "svg",
  "src": "media/shield.svg"

]

四、安全增强措施
数据加密:所有敏感数据在存储和传输过程中都进行加密

权限控制:严格限制应用权限,遵循最小权限原则

输入验证:对所有输入数据进行严格验证和过滤

安全审计:记录关键操作日志用于安全审计

隐私保护:用户数据本地优先处理,减少不必要的数据传输

五、总结

本安全版快递取件助手实现了:
端到端加密:保障用户数据全流程安全

隐私保护:最小化数据收集和使用

安全通信:所有设备间通信加密传输

权限控制:精细化权限管理

通过HarmonyOS的安全框架和加密能力,我们构建了一个既便捷又安全的快递管理工具,在提供便利服务的同时,充分保障用户隐私和数据安全。

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
已于2025-6-20 13:30:53修改
收藏
回复
举报
回复
    相关推荐