【问题标题】:Flutter: Can't use any plugin in onBackgroundMessageFlutter:无法在 onBackgroundMessage 中使用任何插件
【发布时间】:2020-07-18 21:49:14
【问题描述】:

我正在使用 Firebase 推送通知,并且我想在触发 onBackgroundMessage 时执行我的一些代码。它实际上被触发了,因为我在控制台中打印,但我尝试使用几个插件但没有运气。每次出现类似(未处理的异常:MissingPluginException(未找到通道flutter_ringtone_player上的方法播放的实现))时,我都会收到错误消息。我相信这是因为在应用程序的后台状态中没有应用程序的上下文,但是这个功能有什么用,我实际上可以在其中做什么?

我想在 onBackgroundMessage 被触发时播放声音。

    super.initState();

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
      },
      onBackgroundMessage: myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
      },
    );

static Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {        
  FlutterRingtonePlayer.play(
    android: AndroidSounds.notification,
    ios: IosSounds.glass,
    looping: true, // Android only - API >= 28
    volume: 0.8, // Android only - API >= 28
    asAlarm: true, // Android only - all APIs
  );

    print("background message executed");

  return null;
}

【问题讨论】:

    标签: firebase flutter firebase-cloud-messaging


    【解决方案1】:

    尝试在 Android 的 Application 类的 myBackgroundMessageHandler 中注册您需要使用的插件。这是我的 Application.kt 的示例:

    class Application : FlutterApplication(), PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this)
    }
    
    override fun registerWith(registry: PluginRegistry?) {
        PathProviderPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin"))
        FlutterLocalNotificationsPlugin.registerWith(registry?.registrarFor("com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin"))
        FirebaseCloudMessagingPluginRegistrant.registerWith(registry)
    }
    }
    

    【讨论】:

    • 我在哪里可以得到这个“名称” - pub.dev/packages/audioplayers 的 io.flutter.plugins.pathprovider.PathProviderPlugin。我不能得到这个工作。我尝试了 io.flutter.plugins.audioplayers.AudioplayersPlugin,但没有运气。
    • 查看 GeneratedPluginRegistrant.java 文件。您应该能够在其中找到整个包路径。
    • 我实际上使用了另一个插件:pub.dev/packages/assets_audio_player,它正在工作!太感谢了!我相信使用正确的包路径音频播放器也可以工作。惊人的。我会将我的代码粘贴到答案中。
    【解决方案2】:

    这是一个工作代码。当设备收到推送通知(Firebase)时,即使应用关闭,也会执行 onBackgroundMessage 并播放自定义声音。

    ma​​in.dart

    static Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {        
        final assetsAudioPlayer = AssetsAudioPlayer();
    
        assetsAudioPlayer.open(
            Audio("assets/audio/alarm.mp3"),
        );
    
        print("sound played");
    
        return null;
      }
    
      void initState() {
        super.initState();
    
        _firebaseMessaging.configure(
          onMessage: (Map<String, dynamic> message) async {
            print("onMessage: $message");
          },
          onLaunch: (Map<String, dynamic> message) async {
            print("onLaunch: $message");
          },
          onResume: (Map<String, dynamic> message) async {
            print("onResume: $message");
          },
          onBackgroundMessage: myBackgroundMessageHandler
        );
      }
    

    Application.kt

    import com.github.florent37.assetsaudioplayer.AssetsAudioPlayerPlugin
    
    class Application : FlutterApplication(), PluginRegistrantCallback {
        override fun onCreate() {
            super.onCreate()
            FlutterFirebaseMessagingService.setPluginRegistrant(this)
        }   
    
        override fun registerWith(registry: PluginRegistry) {
            AssetsAudioPlayerPlugin.registerWith(registry?.registrarFor("com.github.florent37.assetsaudioplayer"))
    
            FirebaseCloudMessagingPluginRegistrant.registerWith(registry)
        }
    }
    

    【讨论】:

    • 收到错误“未解析的引用:registerWith”。请帮忙。
    • 适用于 ios 的剂量?
    【解决方案3】:

    为避免此类问题,我建议在 Flutter 上使用最新版本的 firebase_messaging 保持更新(flutter 版本 >= 1.12)。如the official doc中所述:

    如果您使用的是 Flutter Android Embedding V2(Flutter 版本 >= 1.12),那么 Android 不需要额外的集成步骤。

    为了在这种情况下继续使用 firebase,请按照以下步骤操作:

    1. 在您的 pubspec.yaml 文件中,添加这两个依赖项:

      firebase_core: ^0.7.0
      firebase_messaging: ^8.0.0-dev.15  
      
    2. 运行flutter pub get

    代码示例:

    在使用任何 firebase 服务之前,您需要使用 await Firebase.initializeApp();,如 here 所述

    应用在前台时接收 Firebase 推送的代码示例:

    FirebaseMessaging _messaging;
    await Firebase.initializeApp();
      _messaging = FirebaseMessaging.instance;
       //App is in the foreground
    
      FirebaseMessaging.onMessage.listen((RemoteMessage message) {
        print('Got a message, app is in the foreground!');
        print('Message data: ${message.data}');
    
        if (message.notification != null) {
          print('Message also contained a notification: ${message.notification}');
        }
      });
    

    代码示例应用在后台/已终止:

    您需要定义一个顶级函数(一个在类之外的函数)。后者将在消息发生并且应用程序在后台时被调用: 根据the doc,应该是这样的:

    Future<void> _firebaseMessagingBackgroundHandler(
    RemoteMessage message,
    ) async {
       await Firebase.initializeApp();
       print('onBackgroundMessage received: $message');
      
     }
    

    那么,这里会用到上面提到的:

     FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    

    【讨论】:

    • 我的日志显示“收到消息的广播”,但从未触发 onMessage()。有什么想法吗?
    • 得到了它的工作,显然我不得不调用messaging.requestPermission,即使我在android上
    • @Karl 这很奇怪,通常 requestPermission 仅适用于 ios。
    猜你喜欢
    • 2020-06-16
    • 1970-01-01
    • 2020-04-23
    • 2021-04-22
    • 2021-07-24
    • 2022-06-16
    • 2020-06-21
    • 2020-09-18
    • 2020-01-31
    相关资源
    最近更新 更多