DEV Community

linzhongxue
linzhongxue

Posted on

Developing Smart Healthcare Applications Based on HarmonyOS Next: From Health Data Management to Multi-Device Collaboration

Developing Smart Healthcare Applications Based on HarmonyOS Next: From Health Data Management to Multi-Device Collaboration

HarmonyOS Next empowers healthcare application development with robust distributed capabilities and comprehensive service suites. This article combines AppGallery Connect (AGC) services with ArkTS to guide you through building a fully functional smart healthcare prototype, covering core scenarios like health data management, device collaboration, and emergency response.


1. Project Architecture and Initial Configuration

Tech Stack:

  • HarmonyOS SDK 5.0
  • ArkTS Declarative UI
  • AGC Services: Health Kit, Cloud DB, Auth Service

Initialization Steps:

  1. Create an AGC project and enable Health Kit/Cloud DB
  2. Configure health data types (steps, heart rate, blood pressure)
  3. Define Cloud DB object type HealthData
// HealthData.ets  
@Observed  
export class HealthData {  
  @PrimaryKey id: string = '';  // Primary key  
  userId: string = '';          // User ID  
  dataType: string = '';        // e.g., 'heart_rate'  
  value: number = 0;            // Measurement value  
  timestamp: number = 0;        // Unix timestamp  
}  
Enter fullscreen mode Exit fullscreen mode

2. Health Data Collection and Local Storage

Core Capability: Health Kit SDK

// HealthManager.ets  
import { health } from '@kit.HealthKit';  

export class HealthManager {  
  // Request health data permissions  
  static async requestAuth(dataTypes: string[]): Promise<boolean> {  
    try {  
      const result = await health.requestAuthorization({  
        permissions: dataTypes.map(type => ({ type, access: health.AccessType.READ }))  
      });  
      return result.authResult.every(item => item.granted);  
    } catch (err) {  
      console.error(`Permission request failed: ${err.message}`);  
      return false;  
    }  
  }  

  // Query today's heart rate data  
  static async queryTodayHeartRate(): Promise<number[]> {  
    const startTime = new Date().setHours(0, 0, 0, 0);  
    const endTime = Date.now();  

    try {  
      const data = await health.queryHealthData({  
        dataType: 'dataType.heart_rate',  
        startTime,  
        endTime  
      });  
      return data.map(item => item.value); // Return heart rate values  
    } catch (err) {  
      console.error(`Heart rate query error: ${err.message}`);  
      return [];  
    }  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

3. Multi-Device Data Collaboration

Scenario: Real-time heart rate display from watch to phone

1. Watch (Data Collection):

// WatchHeartRateMonitor.ets  
import { distributedKVStore } from '@kit.DistributedDataManagerKit';  

@Entry  
@Component  
struct WatchMonitor {  
  @State heartRate: number = 0;  
  private kvManager: distributedKVStore.KVManager | null = null;  

  onInit() {  
    // Initialize distributed KV store  
    distributedKVStore.createKVManager({ bundleName: 'com.example.medapp' })  
      .then(manager => {  
        this.kvManager = manager;  
        return manager.getKVStore('health_store');  
      });  

    // Subscribe to heart rate updates  
    health.subscribeHealthData({ dataType: 'dataType.heart_rate' }, (data) => {  
      this.heartRate = data[0].value;  
      this.syncToPhone(); // Sync to phone  
    });  
  }  

  private syncToPhone() {  
    const deviceList = this.kvManager?.getAvailableDevices('all') || [];  
    if (deviceList.length > 0) {  
      this.kvManager?.getKVStore('health_store').then(store => {  
        store.put('current_heart_rate', JSON.stringify(this.heartRate),   
          { deviceId: deviceList[0].deviceId } // Send to first paired device  
        );  
      });  
    }  
  }  

  build() {  
    Column() {  
      Text(`Live Heart Rate: ${this.heartRate} BPM`).fontSize(20)  
    }  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

2. Phone (Data Display):

// PhoneDashboard.ets  
@Entry  
@Component  
struct HealthDashboard {  
  @State currentHeartRate: number = 0;  

  onInit() {  
    distributedKVStore.createKVManager({ bundleName: 'com.example.medapp' })  
      .then(manager => manager.getKVStore('health_store'))  
      .then(store => {  
        // Listen for data changes  
        store.on('dataChange', 'current_heart_rate', (data) => {  
          this.currentHeartRate = JSON.parse(data.value);  
        });  
      });  
  }  

  build() {  
    Column() {  
      HealthMetricCard({  
        title: 'Live Heart Rate',  
        value: `${this.currentHeartRate} BPM`  
      })  
    }  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

4. Emergency Medical Response System

Integrated Capabilities:

  • Geolocation
  • AGC Cloud Functions for SMS alerts
  • System call service
// EmergencyService.ets  
import { cloud } from '@kit.AGConnectCloudKit';  

@Entry  
@Component  
struct EmergencyButton {  
  private location: string = 'Locating...';  

  private async getLocation() {  
    try {  
      const loc = await geolocation.getCurrentLocation();  
      this.location = `Lat:${loc.latitude}, Lon:${loc.longitude}`;  
    } catch (err) {  
      console.error(`Location error: ${err.message}`);  
    }  
  }  

  private triggerEmergency() {  
    // 1. Trigger cloud emergency alert  
    cloud.function('emergency-alert').call({  
      location: this.location,  
      userId: 'user123'  
    });  

    // 2. Auto-dial emergency number  
    telephone.dial({ phoneNumber: '120', confirm: false });  
  }  

  build() {  
    Column() {  
      Button('EMERGENCY CALL')  
        .backgroundColor('#FF5252')  
        .size({ width: 200, height: 200 })  
        .onClick(() => {  
          this.getLocation();  
          this.triggerEmergency();  
        })  
      Text(`Location: ${this.location}`).margin(10)  
    }  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

5. Offline Sync & Cloud Backup

AGC Cloud DB Implementation:

// CloudSyncManager.ets  
import { cloudDB } from '@kit.AGConnectCloudDBKit';  

export class CloudSyncManager {  
  private cloudDBZone: cloudDB.CloudDBZone | null = null;  

  async initCloudDB() {  
    try {  
      const agcCloudDB = await cloudDB.getAGConnectCloudDB();  
      this.cloudDBZone = await agcCloudDB.openCloudDBZone(  
        new cloudDB.CloudDBZoneConfig('HealthDataZone')  
      );  
    } catch (err) {  
      console.error(`CloudDB init failed: ${err.message}`);  
    }  
  }  

  // Upload health data  
  async upsertHealthData(data: HealthData) {  
    try {  
      await this.cloudDBZone?.upsertData(  
        [data],   
        cloudDB.ConflictResolvePolicy.LOCAL_LAST // Local-first conflict resolution  
      );  
    } catch (err) {  
      console.error(`Data upload failed: ${err.message}`);  
    }  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

6. Privacy & Security Compliance

Critical Implementation:

  1. Dynamic Permission Requests
   async requestCriticalPermissions() {  
     const atManager = abilityAccessCtrl.createAtManager();  
     await atManager.requestPermissionsFromUser(  
       getContext(),   
       ['ohos.permission.HEALTH_DATA', 'ohos.permission.LOCATION']  
     );  
   }  
Enter fullscreen mode Exit fullscreen mode
  1. Encrypted Data Transmission
   <!-- network_config.xml -->  
   <network-security>  
     <domain-config cleartextTrafficPermitted="false">  
       <domain>health-api.example.com</domain>  
       <trust-anchors>  
         <certificates src="@raw/medical_ca"/>  
       </trust-anchors>  
     </domain-config>  
   </network-security>  
Enter fullscreen mode Exit fullscreen mode

7. Project Expansion Paths

  1. AI Health Predictions
   const analyzer = hmsHealth.createHeartRateAnalyzer();  
   analyzer.on('result', (event) => {  
     if (event.irregular) showAlert('Abnormal heart rhythm detected!');  
   });  
Enter fullscreen mode Exit fullscreen mode
  1. Medication Reminders
   backgroundTaskManager.startBackgroundRunning(  
     context,  
     backgroundTaskManager.BackgroundMode.DATA_TRANSFER,  
     { notificationTitle: 'Medication Reminder' }  
   );  
Enter fullscreen mode Exit fullscreen mode
  1. Family Health Sharing
   health.createHealthDataShare().shareData({  
     dataTypes: ['dataType.heart_rate'],  
     targetUser: 'family_user@example.com'  
   });  
Enter fullscreen mode Exit fullscreen mode

Conclusion: Building Next-Gen Healthcare Ecosystems

HarmonyOS Next revolutionizes medical applications through:

  1. Seamless Cross-Device Experience Automated data flow across measurement → analysis → alerting
  2. Real-Time Health Monitoring Millisecond-level response to physiological anomalies
  3. Hardware-Level Security Encryption for sensitive medical data

Top comments (0)

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