Flutter集成Azure Notification Hub遇问题 求最优方案及插件推荐
Flutter集成Azure Notification Hub 解决方案与建议
一、最优方案:官方原生集成+Flutter桥接
这个方案能彻底解决你遇到的MissingPluginException问题,核心是补全Android原生端的配置与通道实现:
Android原生FCM基础配置
- 在
android/app/src/main/AndroidManifest.xml中添加FCM服务声明:<service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> - 创建
MyFirebaseMessagingService类继承FirebaseMessagingService,重写onNewToken获取FCM令牌,重写onMessageReceived处理前台通知消息。
- 在
实现Flutter MethodChannel方法
- 在
MainActivity.kt(或Java)中注册指定通道,并实现getLaunchAction方法,处理应用从通知启动时的参数:class MainActivity : FlutterActivity() { private val CHANNEL = "com.myorg.myapp/notificationaction" override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> if (call.method == "getLaunchAction") { val action = intent.extras?.getString("action") result.success(action) intent.removeExtra("action") // 清空参数避免重复处理 } else { result.notImplemented() } } } }
- 在
Flutter端核心逻辑
- 使用
firebase_messaging插件获取FCM令牌,直接通过HTTP请求将令牌注册到Azure Notification Hub,或传给Node.js后端处理:final fcmToken = await FirebaseMessaging.instance.getToken(); // 此处可选择直接调用Azure REST API注册,或调用后端接口
- 使用
二、替代方案:后端托管设备注册与通知触发
如果不想处理Flutter原生插件的复杂度,可将设备注册、通知触发全交给Node.js后端,Flutter端仅需完成FCM令牌获取并上传:
Flutter端简化逻辑
- 仅需获取FCM令牌,调用后端接口完成上传:
final fcmToken = await FirebaseMessaging.instance.getToken(); await http.post( Uri.parse('https://your-backend.com/api/register-device'), body: {'token': fcmToken, 'userId': 'user123'}, );
- 仅需获取FCM令牌,调用后端接口完成上传:
Node.js后端实现
- 设备注册:调用Azure Notification Hub REST API完成注册,需生成SAS签名作为请求头:
const axios = require('axios'); const crypto = require('crypto'); // 生成Azure SAS签名 function generateSasToken(resourceUri, keyName, key) { const expires = Math.floor(Date.now() / 1000) + 3600; // 1小时有效期 const stringToSign = encodeURIComponent(resourceUri) + '\n' + expires; const hmac = crypto.createHmac('sha256', Buffer.from(key, 'base64')); const signature = hmac.update(stringToSign).digest('base64'); return `SharedAccessSignature sr=${encodeURIComponent(resourceUri)}&sig=${encodeURIComponent(signature)}&se=${expires}&skn=${keyName}`; } // 注册设备到Azure Notification Hub async function registerDevice(fcmToken, userId) { const hubName = 'your-hub-name'; const namespace = 'your-namespace'; const keyName = 'DefaultFullSharedAccessSignature'; const key = 'your-access-key'; const resourceUri = `https://${namespace}.servicebus.windows.net/${hubName}`; const sasToken = generateSasToken(resourceUri, keyName, key); const registration = { platform: 'gcm', pushChannel: fcmToken, tags: [`userId:${userId}`] }; await axios.post( `${resourceUri}/registrations/?api-version=2015-01`, registration, { headers: { 'Authorization': sasToken, 'Content-Type': 'application/json' } } ); } - 触发通知:通过REST API向指定标签或所有设备发送通知:
async function sendNotification(userId, title, body) { const hubName = 'your-hub-name'; const namespace = 'your-namespace'; const keyName = 'DefaultFullSharedAccessSignature'; const key = 'your-access-key'; const resourceUri = `https://${namespace}.servicebus.windows.net/${hubName}`; const sasToken = generateSasToken(resourceUri, keyName, key); const payload = { notification: { title, body }, data: { action: 'open_target_screen' } }; await axios.post( `${resourceUri}/messages/?api-version=2015-01`, payload, { headers: { 'Authorization': sasToken, 'Content-Type': 'application/json', 'ServiceBusNotification-Format': 'gcm' }, params: { tag: `userId:${userId}` } // 按用户标签发送 } ); }
- 设备注册:调用Azure Notification Hub REST API完成注册,需生成SAS签名作为请求头:
三、关键注意事项
- 原生配置不可省略:只要涉及Flutter与原生的交互(比如获取通知启动动作),必须完成Android原生端的通道方法实现,否则必然出现
MissingPluginException。 - Azure配置验证:再次确认FCM服务器密钥已正确关联到Azure Notification Hub,且Hub的访问策略权限足够(至少允许注册和发送操作)。
- 令牌刷新处理:FCM令牌会定期刷新,需在
onNewToken回调中重新上传令牌到后端或Azure,保证注册信息实时有效。
内容的提问来源于stack exchange,提问作者vetti
相关产品推荐
相关产品推荐

