DEV Community

linzhongxue
linzhongxue

Posted on

Developing a Smart Community Life Assistant Based

Developing a Smart Community Life Assistant Based on HarmonyOS Next


I. Scenario-Driven: When HarmonyOS Meets Community Life

Imagine this scenario: The building door automatically recognizes residents and unlocks in the morning; your phone alerts you when packages arrive; all residents receive real-time water outage warnings... All this becomes possible through HarmonyOS Next’s distributed capabilities. This tutorial will use AppGallery Connect and ArkTS to develop a full-scenario life assistant featuring smart access control, property payments, community alerts, and more – truly integrating technology into daily life.


II. Three-Step Environment Setup

Essential Tools:

  • DevEco Studio 4.1 (with built-in HarmonyOS SDK 5.0)
  • Activated AppGallery Connect account

Initialization Process:

  1. Create a project in the AGC console, enabling Cloud Functions and Cloud DB
  2. Check "Super Visual" low-code mode when creating the Ability project
  3. Configure module.json5 with life service permissions:
"abilities": [{  
  "permissions": [  
    "ohos.permission.ACCESS_DOOR_CONTROL",  
    "ohos.permission.RECEIVE_COMMUNITY_MSG"  
  ]  
}]  
Enter fullscreen mode Exit fullscreen mode

III. Core Function Implementation

1. Smart Access Control System

Features: Face recognition + remote unlocking

// DoorAccess.ets  
import doorControl from '@ohos.doorControl';  
import faceAuth from '@ohos.faceAuth';  

@Entry  
@Component  
struct SmartDoorPanel {  
  @State doorStatus: string = "locked"  

  // Unlock via face recognition  
  async unlockByFace() {  
    try {  
      const result = await faceAuth.auth({ challenge: "Community Access" });  
      if (result.code === 0) {  
        await doorControl.unlock("main_gate");  
        this.doorStatus = "unlocked";  
        console.info("Face recognition successful, door unlocked");  
      }  
    } catch (err) {  
      console.error("Recognition failed: " + err.message);  
    }  
  }  

  // Remote unlock (visitor function)  
  remoteUnlock(visitorId: string) {  
    cloud.function('verifyVisitor')  
      .call({ visitorId })  
      .then(() => doorControl.unlock("side_gate"))  
  }  

  build() {  
    Column() {  
      Button("Unlock with Face")  // 实际开发需国际化处理  
        .onClick(() => this.unlockByFace())  
        .visibility(this.doorStatus === "locked" ? Visibility.Visible : Visibility.None)  

      Text(`Access Status: ${this.doorStatus}`)  
        .fontColor(this.doorStatus === "locked" ? Color.Red : Color.Green)  
    }  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

2. Property Payment System

Innovation: Automatic bill recognition + cross-device payment

// PropertyPayment.ets  
import billscanner from '@ohos.billscanner';  
import pay from '@ohos.pay';  

export class PaymentService {  
  // Paper bill scanning  
  async scanBill(image: image.PixelMap) {  
    const result = await billscanner.scan({  
      type: billscanner.BillType.PROPERTY_FEE,  
      image: image  
    });  
    return result.fields;  // Returns amount/house number  
  }  

  // Family group payment (Phone → Tablet confirmation)  
  @DistributedTask("family-payment")  
  async familyGroupPay(order: Order) {  
    const devices = deviceManager.getTrustedDevices();  
    // Push payment requests to family devices  
    devices.forEach(device => {  
      distributedDevice.sync(device.id, "payment-request", order);  
    });  
  }  

  // Payment result callback  
  onPaymentResult(callback: (result: PaymentResult) => void) {  
    distributedDevice.on("payment-result", callback);  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

3. Community Notification Center

Highlights: Tiered alerts + emergency broadcasts

// NoticeCenter.ets  
import notification from '@ohos.notification';  
import geofence from '@ohos.geofence';  

@Component  
struct CommunityAlerts {  
  // Location-based alerts  
  setupLocationBasedAlerts() {  
    geofence.on('enter', (fence) => {  
      if (fence.id === "garbage_station") {  
        notification.show({  
          content: "Near garbage station. Today's sorting: Food/Other"  
        });  
      }  
    });  
  }  

  // Emergency broadcasts (triggered by property)  
  @ReceiveBroadcast("emergency_alert")  
  onEmergencyAlert(alert: {type: string, msg: string}) {  
    notification.show({  
      title: "【URGENT】" + alert.type,  
      content: alert.msg,  
      importance: notification.Importance.HIGH,  
      isAlertOnce: true  // Avoid duplicate alerts  
    });  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

4. Neighborhood Social Module

Special Feature: Interest-based sharing

// SocialHub.ets  
import social from '@ohos.social';  

@Entry  
@Component  
struct InterestCircle {  
  @StorageLink('userInterests') interests: string[] = []  

  // Join interest circle  
  joinCircle(circleId: string) {  
    social.joinGroup(circleId).then(() => {  
      this.interests.push(circleId);  
    });  
  }  

  // Post to circle  
  @DistributedPersistence("post_cache")  
  async postToCircle(content: string, images: string[]) {  
    const post = {  
      content,  
      images,  
      circle: this.interests[0]  // Default to recent circle  
    };  
    await cloud.database().collection('posts').add(post);  
  }  

  build() {  
    DynamicContainer()  
      .dataSource(this.interests.map(id => circleData[id]))  
      .builder((circle) => CircleCard({ circle }))  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

IV. Key Technology Breakdown

1. Atomic Service Implementation

graph TB  
A[Payment Service] -->|Launched| B[Phone]  
A -->|Launched| C[Smartwatch]  
A -->|Launched| D[Car Screen]  
Enter fullscreen mode Exit fullscreen mode

Implementation:

// module.json5  
"abilities": [{  
  "forms": [{  
    "name": "quick_pay",  
    "description": "Quick Payment",  
    "type": "service",  
    "uiSyntax": "hml"  
  }]  
}]  
Enter fullscreen mode Exit fullscreen mode

2. Cross-Device Data Sync

// Family device synchronization  
const syncOptions = {  
  mode: distributedData.SyncMode.PUSH_PULL,  
  filters: ["payment_status", "door_events"]  
};  
distributedData.sync(syncOptions);  
Enter fullscreen mode Exit fullscreen mode

3. Device-Cloud Collaboration

Device → HarmonyOS SoftBus → AppGallery Connect → Property Management  
        │                  │  
    Local response      Big data analytics  
Enter fullscreen mode Exit fullscreen mode

V. Performance Optimization

1. Rendering Optimization

// Conditional rendering reduces DOM nodes  
if (this.hasNewNotice) {  
  BannerNotice({ urgency: this.noticeLevel })  
}  
Enter fullscreen mode Exit fullscreen mode

2. Data Loading Strategy

// Paginated community feeds  
LazyForEach(this.postDataSource, (post) => {  
  PostItem({ data: post })  
}, post => post.id)  
Enter fullscreen mode Exit fullscreen mode

3. Power Saving Techniques

// On-demand location services  
geofence.enable().then(() => {  
  // Disable after obtaining geofence info  
  geofence.disable();    
});  
Enter fullscreen mode Exit fullscreen mode

VI. Deployment Guide

1. Cloud Service Configuration

  1. Enable "Life Services" in AGC console
  2. Configure bill recognition templates
  3. Set payment callback URLs

2. Security Hardening

  • End-to-end encryption for access control
  • CAPTCHA for payment interfaces
  • Local encryption for sensitive data

3. Release Checklist

  • Property cooperation agreements
  • Payment license number
  • Privacy policy (with data collection details)

VII. Extended Scenarios

  1. AR Navigation: Point phone at buildings to see package locker locations
  2. Smart Home Integration: Lights turn on automatically when entering home
  3. Elderly Care: Automatic alerts for unusual inactivity patterns

Conclusion: Technology Warms Life

This project demonstrates how HarmonyOS Next integrates fragmented services into a unified experience. Atomic services make functions universally accessible, distributed capabilities break device barriers, and ArkTS streamlines development. When technology truly understands human needs, smart communities become reality.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.