Cangjie/HarmonyOS-Examples 消息推送服务:Firebase与厂商推送
Cangjie/HarmonyOS-Examples 消息推送服务:Firebase与厂商推送
【免费下载链接】HarmonyOS-Examples 本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计! 项目地址: https://gitcode.com/Cangjie/HarmonyOS-Examples
前言:消息推送在移动应用中的重要性
在移动应用生态中,消息推送(Push Notification)是连接用户与应用的重要桥梁。无论是社交应用的即时消息、电商平台的促销通知,还是新闻客户端的实时资讯,消息推送都扮演着不可或缺的角色。对于鸿蒙(HarmonyOS)开发者而言,构建稳定高效的消息推送体系是提升用户体验的关键环节。
本文将深入探讨在Cangjie/HarmonyOS-Examples项目中如何集成Firebase Cloud Messaging(FCM)和各大厂商推送服务,为鸿蒙应用开发者提供完整的消息推送解决方案。
消息推送架构设计
整体架构图
多通道推送策略
为了确保消息的高到达率,我们采用多通道推送策略:
Firebase Cloud Messaging集成
环境配置
首先在项目的entry/oh-package.json5
中添加Firebase依赖:
{ \"dependencies\": { \"@hw-agconnect/hmcore\": \"^1.0.0\", \"@hw-agconnect/push-hm\": \"^1.0.0\", \"firebase\": \"^10.0.0\" }}
Firebase初始化配置
创建FirebaseService.ets
服务类:
import firebase from \'firebase/app\';import \'firebase/messaging\';export class FirebaseService { private static instance: FirebaseService; private messaging: any; private constructor() { this.initializeFirebase(); } public static getInstance(): FirebaseService { if (!FirebaseService.instance) { FirebaseService.instance = new FirebaseService(); } return FirebaseService.instance; } private initializeFirebase(): void { const firebaseConfig = { apiKey: \"your-api-key\", authDomain: \"your-project.firebaseapp.com\", projectId: \"your-project-id\", storageBucket: \"your-project.appspot.com\", messagingSenderId: \"123456789\", appId: \"your-app-id\" }; try { firebase.initializeApp(firebaseConfig); this.messaging = firebase.messaging(); this.setupMessageHandling(); } catch (error) { console.error(\'Firebase initialization error:\', error); } } private setupMessageHandling(): void { // 处理前台消息 this.messaging.onMessage((payload: any) => { console.log(\'Message received in foreground:\', payload); this.showNotification(payload); }); // 处理后台消息 self.addEventListener(\'push\', (event: any) => { const payload = event.data.json(); this.showNotification(payload); }); } private showNotification(payload: any): void { const notification = { title: payload.notification?.title || \'新消息\', body: payload.notification?.body || \'您有一条新消息\', icon: \'/common/images/icon.png\', data: payload.data }; // 鸿蒙通知API调用 // @ts-ignore const notifyManager = notify.getNotificationManager(); const request: notify.NotificationRequest = { content: { contentType: notify.ContentType.NOTIFICATION_TEXT, normal: { title: notification.title, text: notification.body, additionalText: \'\', id: Date.now() } }, id: Date.now(), slotType: notify.SlotType.SOCIAL_COMMUNICATION }; notifyManager.publish(request).then(() => { console.log(\'Notification published successfully\'); }).catch((error: any) => { console.error(\'Failed to publish notification:\', error); }); } public async getToken(): Promise { try { const token = await this.messaging.getToken(); console.log(\'FCM Token:\', token); return token; } catch (error) { console.error(\'Error getting FCM token:\', error); throw error; } } public async deleteToken(): Promise { try { const token = await this.getToken(); await this.messaging.deleteToken(token); } catch (error) { console.error(\'Error deleting FCM token:\', error); } }}
厂商推送服务集成
华为推送服务集成
import agconnect from \'@hw-agconnect/hmcore\';import push from \'@hw-agconnect/push-hm\';export class HuaweiPushService { private static instance: HuaweiPushService; public static getInstance(): HuaweiPushService { if (!HuaweiPushService.instance) { HuaweiPushService.instance = new HuaweiPushService(); } return HuaweiPushService.instance; } public async initialize(): Promise { try { // 初始化AGC连接 await agconnect.instance().init(); // 获取推送token push.getInstance().getToken().then((data: any) => { console.log(\'Huawei Push Token:\', data.token); this.registerTokenToServer(data.token); }).catch((error: any) => { console.error(\'Get Huawei push token failed:\', error); }); // 监听消息到达 push.getInstance().on(\'pushMessage\', (message: any) => { this.handlePushMessage(message); }); } catch (error) { console.error(\'Huawei Push initialization failed:\', error); } } private handlePushMessage(message: any): void { console.log(\'Received Huawei push message:\', message); const notification = { title: message.notification?.title || \'华为推送\', body: message.notification?.body || \'您有一条新消息\', data: message.data }; this.showHuaweiNotification(notification); } private showHuaweiNotification(notification: any): void { // 华为设备专用通知显示逻辑 // @ts-ignore const notifyManager = notify.getNotificationManager(); const request: notify.NotificationRequest = { content: { contentType: notify.ContentType.NOTIFICATION_TEXT, normal: { title: `[华为] ${notification.title}`, text: notification.body, additionalText: \'来自华为推送服务\', id: Date.now() } }, id: Date.now(), slotType: notify.SlotType.SOCIAL_COMMUNICATION }; notifyManager.publish(request); } private registerTokenToServer(token: string): void { // 将token注册到应用服务器 console.log(\'Registering Huawei token to server:\', token); }}
多厂商推送统一管理
创建PushManager.ets
统一管理所有推送服务:
import { FirebaseService } from \'./FirebaseService\';import { HuaweiPushService } from \'./HuaweiPushService\';export class PushManager { private static instance: PushManager; private firebaseService: FirebaseService; private huaweiService: HuaweiPushService; private currentToken: string = \'\'; private constructor() { this.firebaseService = FirebaseService.getInstance(); this.huaweiService = HuaweiPushService.getInstance(); } public static getInstance(): PushManager { if (!PushManager.instance) { PushManager.instance = new PushManager(); } return PushManager.instance; } public async initialize(): Promise { console.log(\'Initializing push services...\'); // 根据设备类型选择推送服务 const deviceBrand = await this.getDeviceBrand(); switch (deviceBrand) { case \'huawei\': await this.huaweiService.initialize(); break; case \'xiaomi\': await this.initializeXiaomiPush(); break; case \'oppo\': await this.initializeOppoPush(); break; case \'vivo\': await this.initializeVivoPush(); break; default: // 默认使用Firebase await this.firebaseService.getToken(); break; } } private async getDeviceBrand(): Promise { try { // @ts-ignore const deviceInfo = deviceInfo.getDeviceInfo(); const brand = deviceInfo.brand.toLowerCase(); return brand; } catch (error) { console.error(\'Get device brand failed:\', error); return \'unknown\'; } } private async initializeXiaomiPush(): Promise { // 小米推送初始化逻辑 console.log(\'Initializing Xiaomi Push Service\'); // 实现小米推送SDK集成 } private async initializeOppoPush(): Promise { // OPPO推送初始化逻辑 console.log(\'Initializing OPPO Push Service\'); // 实现OPPO推送SDK集成 } private async initializeVivoPush(): Promise { // vivo推送初始化逻辑 console.log(\'Initializing vivo Push Service\'); // 实现vivo推送SDK集成 } public getCurrentToken(): string { return this.currentToken; } public async unsubscribe(): Promise { // 取消所有推送订阅 try { await this.firebaseService.deleteToken(); // 其他厂商推送的取消订阅逻辑 } catch (error) { console.error(\'Unsubscribe push failed:\', error); } }}
消息处理与业务逻辑集成
消息类型定义
export interface PushMessage { messageId: string; title: string; body: string; data?: Record; timestamp: number; channel: \'fcm\' | \'huawei\' | \'xiaomi\' | \'oppo\' | \'vivo\'; priority: \'high\' | \'normal\' | \'low\';}export enum MessageType { TEXT_MESSAGE = \'text\', IMAGE_MESSAGE = \'image\', SYSTEM_NOTICE = \'system\', PROMOTION = \'promotion\', TRANSACTION = \'transaction\'}
消息处理器
export class MessageHandler { private static instance: MessageHandler; public static getInstance(): MessageHandler { if (!MessageHandler.instance) { MessageHandler.instance = new MessageHandler(); } return MessageHandler.instance; } public handleMessage(message: PushMessage): void { console.log(\'Processing push message:\', message); // 根据消息类型进行不同的处理 switch (this.getMessageType(message)) { case MessageType.TEXT_MESSAGE: this.handleTextMessage(message); break; case MessageType.IMAGE_MESSAGE: this.handleImageMessage(message); break; case MessageType.SYSTEM_NOTICE: this.handleSystemNotice(message); break; case MessageType.PROMOTION: this.handlePromotion(message); break; case MessageType.TRANSACTION: this.handleTransaction(message); break; default: this.handleDefaultMessage(message); } // 更新应用角标 this.updateAppBadge(); } private getMessageType(message: PushMessage): MessageType { const data = message.data || {}; return data.type || MessageType.TEXT_MESSAGE; } private handleTextMessage(message: PushMessage): void { // 文本消息处理逻辑 this.showNotification(message); this.updateConversationList(message); } private handleImageMessage(message: PushMessage): void { // 图片消息处理逻辑 this.showNotification(message); this.downloadImage(message.data?.imageUrl); } private handleSystemNotice(message: PushMessage): void { // 系统通知处理 this.showSystemNotification(message); this.logSystemEvent(message); } private showNotification(message: PushMessage): void { // 统一的通知显示逻辑 const notificationConfig = { title: message.title, content: message.body, extra: message.data }; // 调用鸿蒙通知API this.displayHarmonyNotification(notificationConfig); } private displayHarmonyNotification(config: any): void { // @ts-ignore const notifyManager = notify.getNotificationManager(); const request: notify.NotificationRequest = { content: { contentType: notify.ContentType.NOTIFICATION_TEXT, normal: { title: config.title, text: config.content, additionalText: this.getChannelName(config.extra?.channel), id: Date.now() } }, id: Date.now(), slotType: notify.SlotType.SOCIAL_COMMUNICATION }; notifyManager.publish(request); } private getChannelName(channel: string): string { const channelMap: Record = { \'fcm\': \'Firebase推送\', \'huawei\': \'华为推送\', \'xiaomi\': \'小米推送\', \'oppo\': \'OPPO推送\', \'vivo\': \'vivo推送\' }; return channelMap[channel] || \'推送消息\'; } private updateAppBadge(): void { // 更新应用角标数字 // @ts-ignore badge.setBadgeNumber(badge.getBadgeNumber() + 1); }}
性能优化与最佳实践
推送服务选择策略
消息去重机制
export class MessageDeduplicator { private receivedMessages: Set = new Set(); private readonly DEDUPLICATION_WINDOW = 5 * 60 * 1000; // 5分钟 public isDuplicate(message: PushMessage): boolean { const messageKey = this.getMessageKey(message); if (this.receivedMessages.has(messageKey)) { return true; } this.receivedMessages.add(messageKey); // 定时清理过期消息 setTimeout(() => { this.receivedMessages.delete(messageKey); }, this.DEDUPLICATION_WINDOW); return false; } private getMessageKey(message: PushMessage): string { return `${message.messageId}_${message.timestamp}_${message.channel}`; } public clear(): void { this.receivedMessages.clear(); }}
电池优化策略
export class BatteryOptimizer { public static optimizePushService(): void { // 根据设备电量状态调整推送策略 this.getBatteryStatus().then(status => { if (status.level < 20) { this.reducePushFrequency(); } else if (status.level < 10) { this.disableNonCriticalPush(); } }); } private static async getBatteryStatus(): Promise { try { // @ts-ignore return await battery.getBatteryInfo(); } catch (error) { console.error(\'Get battery status failed:\', error); return { level: 100 }; // 默认满电 } } private static reducePushFrequency(): void { // 降低推送频率逻辑 console.log(\'Reducing push frequency due to low battery\'); } private static disableNonCriticalPush(): void { // 禁用非关键推送 console.log(\'Disabling non-critical push due to critical battery level\'); }}
测试与调试
推送测试工具
export class PushTester { public static testAllChannels(): void { const testMessages = [ { title: \'Firebase测试消息\', body: \'这是一条来自Firebase的测试消息\', channel: \'fcm\' as const }, { title: \'华为推送测试\', body: \'这是一条来自华为推送的测试消息\', channel: \'huawei\' as const } ]; testMessages.forEach((message, index) => { setTimeout(() => { this.sendTestMessage(message); }, index * 2000); }); } private static sendTestMessage(message: any): void { const testMessage: PushMessage = { messageId: `test_${Date.now()}`, title: message.title, body: message.body, timestamp: Date.now(), channel: message.channel, priority: \'normal\' }; MessageHandler.getInstance().handleMessage(testMessage); } public static generateTestReport(): void { const report = { timestamp: new Date().toISOString(), deviceInfo: this.getDeviceInfo(), pushServices: this.getPushServiceStatus(), recommendations: this.generateRecommendations() }; console.log(\'Push Test Report:\', JSON.stringify(report, null, 2)); } private static getDeviceInfo(): any { // 获取设备信息 return {
【免费下载链接】HarmonyOS-Examples 本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计! 项目地址: https://gitcode.com/Cangjie/HarmonyOS-Examples
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考