I'm trying to use flutter_local_notifications with google firebase on flutter. I followed oficial guides, wasted a week on it, but it stiil does not work. Notifications show up but when I tap on them, none of three events (onMessage, onResume, onLaunch) does not evaluate. Here is what my files contain:
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 (I have error in it):
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"))
}
}
that's an error I recieve in Application.kt
Android/app/src/main/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>
The problem was in declaring PushNotificationManager variable. I declared it in local method, so it was "destroyed" when method was done