如何在Flutter后台通过Method Channel调用API并控制Android/iOS端Onesignal通知
Flutter后台通过Method Channel交互API并控制OneSignal通知显示
下面分步骤实现需求,涵盖Flutter侧、Android原生和iOS原生的代码示例:
一、Flutter侧:后台Method Channel与API调用实现
1. 定义Method Channel并注册回调
在Flutter中创建专属Method Channel,用于和原生端后台交互,并实现API调用逻辑:
import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:flutter/services.dart'; // 定义Method Channel名称,需和原生端保持一致 const MethodChannel _backgroundChannel = MethodChannel('com.your.app/notification_check'); // 后台API调用逻辑,返回是否允许显示通知的布尔值 Future<bool> _checkNotificationPermission() async { try { // 调用目标API替换为你的实际接口地址 final response = await http.get(Uri.parse('https://your-api-domain.com/api/allow-notification')); if (response.statusCode == 200) { final responseData = jsonDecode(response.body); // 根据API返回字段判断是否允许显示通知 return responseData['allow_show'] ?? false; } // API请求失败默认返回不允许 return false; } catch (e) { // 捕获网络异常或解析错误,默认不允许显示通知 return false; } } // 注册Method Channel回调,建议在main函数初始化时调用 void setupBackgroundChannelHandler() { _backgroundChannel.setMethodCallHandler((call) async { if (call.method == 'requestNotificationPermission') { return await _checkNotificationPermission(); } throw MissingPluginException('Method not implemented'); }); }
二、Android原生端:根据API响应控制OneSignal通知
1. 配置OneSignal后台回调与Method Channel交互
在Android的Application类中初始化OneSignal,并在通知接收回调中调用Flutter的Method Channel获取结果,决定是否显示通知:
import android.app.Application import com.onesignal.OSNotificationReceivedEvent import com.onesignal.OneSignal import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.dart.DartExecutor import io.flutter.plugin.common.MethodChannel class App : Application(), OneSignal.OSNotificationReceivedHandler { private lateinit var backgroundChannel: MethodChannel override fun onCreate() { super.onCreate() // 初始化OneSignal,替换为你的App ID OneSignal.initWithContext(this) OneSignal.setAppId("YOUR_ONESIGNAL_APP_ID") OneSignal.setNotificationReceivedHandler(this) // 初始化Flutter Engine用于后台Method Channel调用 val flutterEngine = FlutterEngine(this) flutterEngine.dartExecutor.executeDartEntrypoint( DartExecutor.DartEntrypoint.createDefault() ) backgroundChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.your.app/notification_check") } override fun notificationReceived(event: OSNotificationReceivedEvent) { // 异步调用Flutter侧的权限检查方法 backgroundChannel.invokeMethod("requestNotificationPermission", null, object : MethodChannel.Result { override fun success(result: Any?) { val shouldShow = result as Boolean if (shouldShow) { // 允许显示通知,将原事件传递完成 event.complete(event.notification) } else { // 拒绝显示通知,传递null取消通知 event.complete(null) } } override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) { // 调用失败默认取消通知 event.complete(null) } override fun notImplemented() { event.complete(null) } }) } }
2. 必要权限配置
在AndroidManifest.xml中添加后台运行和网络权限:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
三、iOS原生端:根据API响应控制OneSignal通知
1. 配置OneSignal回调与Method Channel交互
在AppDelegate中初始化OneSignal,并实现通知接收回调,调用Flutter侧的方法获取结果:
import UIKit import Flutter import OneSignal @UIApplicationMain class AppDelegate: FlutterAppDelegate, OSNotificationReceivedDelegate { private var backgroundChannel: FlutterMethodChannel! override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // 初始化OneSignal,替换为你的App ID OneSignal.setAppId("YOUR_ONESIGNAL_APP_ID") OneSignal.setNotificationReceivedDelegate(self) let controller = window?.rootViewController as! FlutterViewController backgroundChannel = FlutterMethodChannel(name: "com.your.app/notification_check", binaryMessenger: controller.binaryMessenger) GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } func notificationReceived(_ notificationReceivedEvent: OSNotificationReceivedEvent) { // 调用Flutter侧的权限检查方法 backgroundChannel.invokeMethod("requestNotificationPermission", arguments: nil) { result in guard let shouldShow = result as? Bool else { // 结果异常默认取消通知 notificationReceivedEvent.complete(nil) return } if shouldShow { // 允许显示通知 notificationReceivedEvent.complete(notificationReceivedEvent.notification) } else { // 取消通知 notificationReceivedEvent.complete(nil) } } } }
2. 后台模式配置
在Info.plist中添加远程通知后台权限:
<key>UIBackgroundModes</key> <array> <string>remote-notification</string> </array>
四、关键注意事项
- API调用稳定性:Flutter后台环境下网络调用可能受系统限制,需设置合理超时时间,避免阻塞原生通知处理流程。
- OneSignal通知参数:发送静默通知时,Android需携带
data字段,iOS需设置content-available: 1,才能触发后台回调。 - Flutter Engine复用:Android端建议复用Flutter Engine,避免重复初始化带来的性能损耗;iOS端需确保FlutterViewController在后台能正常响应Method Channel调用。
内容的提问来源于stack exchange,提问作者jos Sea
相关产品推荐
相关产品推荐

