Flutter: невозможно использовать плагин в onBackgroundMessage - PullRequest
0 голосов
/ 06 апреля 2020

Я использую Firebase Pu sh Уведомления и хочу выполнить часть моего кода при запуске onBackgroundMessage. Это на самом деле срабатывает, потому что я печатаю в консоли, но я попытался использовать несколько плагинов, но безуспешно. Я получаю сообщение об ошибке каждый раз, когда что-то вроде (Unhandled Exception: 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;
}

Ответы [ 2 ]

0 голосов
/ 08 апреля 2020

Вот рабочий код. Когда устройство получает уведомление pu sh (Firebase), выполняется onBackgroundMessage и воспроизводится собственный звук, даже если приложение закрыто.

main.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)
    }
}
0 голосов
/ 07 апреля 2020

Попробуйте зарегистрировать плагины, которые вам нужно использовать в myBackgroundMessageHandler, в вашем Android классе Application. Вот пример моего 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)
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...