события flutter_local_notifications не работают - PullRequest
0 голосов
/ 06 августа 2020

Я пытаюсь использовать flutter_local_notifications с google firebase при флаттере. Я следил за официальными руководствами, потратил на это неделю, но он все равно не работает. Уведомления появляются, но когда я нажимаю на них, ни одно из трех событий (onMessage, onResume, onLaunch) не оценивается. Вот что содержат мои файлы:

PushNotificationManager.dart:

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class PushNotificationsManager {
  PushNotificationsManager(BuildContext context){
    init(context);
  }
  static String token;
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  bool _initialized = false;

  init(BuildContext context) {
    try{
    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        new FlutterLocalNotificationsPlugin();
        var initAndroid = AndroidInitializationSettings('launcher_icon');
        var initIOS = IOSInitializationSettings();
        InitializationSettings initializationSettings = InitializationSettings(initAndroid, initIOS);
        flutterLocalNotificationsPlugin.initialize(initializationSettings);
        var androidPlatformChannelSpecifics = AndroidNotificationDetails(
          'WheelKeep',
          'WheelKeep',
          'WheelKeep',
          //icon: "launcher_icon",
          enableVibration: true,
          importance: Importance.Max,
          priority: Priority.High,
          playSound: true,
          sound: RawResourceAndroidNotificationSound('serious_strike')
        );

        var iOSPlatformChannelSpecifics = IOSNotificationDetails();

        var platformChannelSpecifics = NotificationDetails(
            androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
        try {
          await flutterLocalNotificationsPlugin.show(
            1,
            message['notification']['title'],
            message['notification']['body'],
            platformChannelSpecifics,
          );
        }
        catch(Exception){
          Exception.toString();
        }
        var p =10;
      },
      /*onBackgroundMessage: (Map<String, dynamic> message) async {
        Navigator.pushNamed(context, '/lock_screen');
        print("onBackground: $message");
      },*/
      onLaunch: (Map<String, dynamic> message) async {
        Navigator.pushNamed(context, '/lock_screen');
        print("onLaunch: $message");
      },
      onResume: (Map<String, dynamic> message) async {
        Navigator.pushNamed(context, '/lock_screen');
        print("onResume: $message");
      },
    );
    }
    catch(Exception){
      Exception.toString();
    }
  }

  Future<String> getToken ()async{
    try {
      token = await _firebaseMessaging.getToken();
    }
    catch(Exception){
      print(Exception.toString());
    }
    return token;
  }

  static Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
    if (message.containsKey('data')) {
      // Handle data message
      final dynamic data = message['data'];
      return data;
    }
    if (message.containsKey('notification')) {
      // Handle notification message
      final dynamic notification = message['notification'];
      return notification;
    }
    return message[''];
    // Or do other work.
  }
}

android / app / build.gradle:


def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new FileNotFoundException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        checkReleaseBuilds false
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "com.example.lockui"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.google.firebase:firebase-analytics:17.4.4'
    implementation 'com.google.firebase:firebase-messaging:20.2.4'

}

android / app / src / main /kotlin/com.example.lockui/Application.kt (у меня есть ошибка):

package com.example.lockui

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this)
    }

    override fun registerWith(registry: PluginRegistry) {
        FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }
}

это ошибка, которую я получаю в Application.kt

Android / приложение / SRC / основной / AndroidManifest. xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.lockui">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:icon="@mipmap/launcher_icon"
        android:label="WheelKeep">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyD5xDubh4kynhFFhDxh9jMxWGn7G9AU6sU" />

        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:windowSoftInputMode="adjustResize"
            tools:targetApi="honeycomb">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

Ответы [ 2 ]

0 голосов
/ 07 августа 2020

Проблема заключалась в объявлении переменной PushNotificationManager. Я объявил это в локальном методе, поэтому он был "уничтожен", когда метод был выполнен

0 голосов
/ 07 августа 2020

В файле манифеста в теге приложения укажите имя вашего приложения для свойства name.

Вот так:

<application
     android:name=".Application"

и содержимое внутри класса приложения должно выглядеть так: введите описание изображения здесь

...