DEV Community

linzhongxue
linzhongxue

Posted on

Smart Community Living App Development Based on HarmonyOS Next

Smart Community Living App Development Based on HarmonyOS Next

1. Application Scenario and Functional Planning

We will create a community living service app addressing residents' daily needs:

  1. Smart Access Control: Mobile NFC emulates access cards
  2. Community Bulletin System: Real-time notifications
  3. Convenient Repair Service: Photo uploads for faulty equipment
  4. Neighborhood Social Platform: Event registration and communication
  5. Smart Parcel Lockers: QR code pickup and package tracking

Technical Architecture:

  • Frontend: ArkUI + ArkTS
  • Backend: AGC CloudDB + Cloud Storage + Push Messaging
  • Device Integration: HarmonyOS Distributed Capabilities

2. Quick Project Setup

ohos create project CommunityLife --template empty:latest --model stage
Enter fullscreen mode Exit fullscreen mode

Project Structure:

entry/src/main/
  ├── ets/
  │   ├── pages/       # Functional pages
  │   ├── components/  # Custom components
  │   ├── service/     # Service modules
  │   └── model/       # Data models
  ├── resources/       # Assets
  └── module.json5     # Configuration
Enter fullscreen mode Exit fullscreen mode

3. Core Function Implementation

1. NFC Smart Access (System Service Integration)
// service/DoorAccessService.ts
import { nfc } from '@ohos.nfc'; 
import { cardEmulation } from '@ohos.nfc.cardEmulation';

// Simulate access card
export function enableVirtualAccessCard() {
  try {
    const ceService = cardEmulation.getHceService();

    // Register access card AID
    ceService.registerAidsForService({
      type: cardEmulation.AidType.ACCESS,
      aids: ['F0010203040506']
    }).then(() => {
      console.info('Access card activated');
    });

    // Handle reader events
    ceService.on('hceCmd', (event) => {
      const response = new Uint8Array([0x90, 0x00]);
      ceService.sendResponse(response);
    });

  } catch (err) {
    console.error(`Activation failed: ${err.message}`);
  }
}
Enter fullscreen mode Exit fullscreen mode
2. Community Bulletin System (CloudDB Integration)
// pages/NoticePage.ets
import { cloud } from '@agconnect/cloud';

@Entry
@Component
struct NoticePage {
  @State notices: Array<Notice> = [];

  loadNotices() {
    const query = cloud.cloudDB()
      .createQuery(Notice)
      .orderByDesc("publishTime");

    cloud.cloudDB().executeQuery(query).then(result => {
      this.notices = result.getSnapshotObjects();
    });
  }

  build() {
    Column() {
      List({ space: 10 }) {
        ForEach(this.notices, (item) => {
          ListItem() {
            Column() {
              Text(item.title).fontSize(18)
              Text(item.content).fontColor(Color.Gray)
              Text(`Published: ${new Date(item.publishTime).toLocaleString()}`)
            }
            .padding(15)
          }
        })
      }
    }
    .onAppear(() => this.loadNotices())
  }
}
Enter fullscreen mode Exit fullscreen mode
3. Property Repair Service (Cloud Storage + OCR)
// pages/RepairPage.ets
import { cloud } from '@agconnect/cloud';
import { image } from '@ohos.multimedia.image';

@Component
struct RepairUploader {
  @State selectedImage?: image.PixelMap;

  async takeRepairPhoto() {
    try {
      const camera = await cameraManager.getCameraInstance();
      const photo = await camera.takePhoto();

      const compressed = await image.createImageSource(photo.uri)
        .createPixelMap({ desiredSize: { width: 800 } });

      this.selectedImage = compressed;

      const storage = cloud.storage();
      const fileRef = storage.ref(`repairs/${new Date().getTime()}.jpg`);
      await fileRef.put(compressed);

      analyzeRepairType(photo.uri); // OCR analysis
    } catch (err) {
      console.error('Upload failed', err);
    }
  }

  build() {
    Column() {
      if (this.selectedImage) {
        Image(this.selectedImage)
          .width('100%')
          .height(200)
      }

      Button('Report Issue')
        .onClick(() => this.takeRepairPhoto())
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
4. Neighborhood Social Platform (Real-time Messaging)
// service/CommunityChat.ts
import { cloud } from '@agconnect/cloud';
import { push } from '@agconnect/push';

export function initChatService() {
  push.on('message', (msg) => {
    showMessageNotification(msg);
  });

  push.subscribe('community_events');
}

export async function sendCommunityAlert(title: string, content: string) {
  const message = {
    title: title,
    body: content,
    data: { type: 'community_alert' }
  };

  await push.send({
    message: message,
    topic: 'all_residents'
  });
}
Enter fullscreen mode Exit fullscreen mode

4. Complete Case: Community Event System

// pages/EventPage.ets
import { cloud } from '@agconnect/cloud';

@Entry
@Component
struct EventPage {
  @State events: Array<CommunityEvent> = [];
  @State joinedEvents: Set<string> = new Set();

  loadEvents() {
    const query = cloud.cloudDB()
      .createQuery(CommunityEvent)
      .whereGreaterThan('endTime', Date.now());

    cloud.cloudDB().executeQuery(query).then(result => {
      this.events = result.getSnapshotObjects();
    });
  }

  joinEvent(eventId: string) {
    cloud.cloudDB().executeUpsert(new Participation({
      eventId: eventId,
      userId: getCurrentUser().uid
    })).then(() => {
      this.joinedEvents.add(eventId);
      console.log('Registration successful');
    });
  }

  build() {
    Column() {
      Text('Community Events').fontSize(24).margin(15)

      List() {
        ForEach(this.events, (event) => {
          ListItem() {
            Row() {
              Image(event.coverUrl).width(80).height(80)

              Column() {
                Text(event.title).fontSize(18)
                Text(`Date: ${new Date(event.startTime).toLocaleDateString()}`)
                Text(`Location: ${event.location}`)
              }

              if (!this.joinedEvents.has(event.id)) {
                Button('Join Now')
                  .onClick(() => this.joinEvent(event.id))
              } else {
                Text('Registered').fontColor(Color.Green)
              }
            }
            .padding(10)
          }
        })
      }
    }
    .onAppear(() => this.loadEvents())
  }
}
Enter fullscreen mode Exit fullscreen mode

5. Performance Optimization

  1. Lazy Data Loading
const query = cloud.cloudDB()
  .createQuery(Notice)
  .limit(10)
  .offset(this.notices.length);
Enter fullscreen mode Exit fullscreen mode
  1. Local Caching
import { dataStorage } from '@ohos.data.storage';

const storage = await dataStorage.getStorage('community_cache');
await storage.put('notices', JSON.stringify(this.notices));
Enter fullscreen mode Exit fullscreen mode
  1. Cross-device Coordination
import { distributedDeviceManager } from '@ohos.distributedHardware.deviceManager';

const deviceList = await distributedDeviceManager.getAvailableDeviceListSync();
deviceList[0].callMethod('openDoor', { doorId: 'main_gate' });
Enter fullscreen mode Exit fullscreen mode

6. Testing and Deployment

Key Tests:

  1. Access card simulation (requires NFC-enabled device)
  2. Large file upload stability (50MB+ images)
  3. Multi-device message synchronization

Cloud Configuration:

  1. Enable CloudDB (CommunityDB) in AGC Console
  2. Configure push certificates (iOS/Android)
  3. Cloud Storage rules:
   {
     "rules": {
       "repairs": {
         "read": true,
         "write": "auth != null"
       }
     }
   }
Enter fullscreen mode Exit fullscreen mode

Conclusion: HarmonyOS Advantages in Living Services

  1. Seamless Device Integration: Real-time sync across phones/tablets/smart screens
  2. Cloud Service Integration: One-stop backend solution with AGC
  3. Peformance Excellence: Sub-second response with ArkTS engine

Extension Ideas:

  • Community group buying system
  • Smart waste sorting guide
  • Home service booking

Top comments (0)

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