Closed creativecreatorormaybenot closed 2 years ago
exact same issue. the error appears when using background notification.
same issue, is there any solution yet?
I run in to error while using @callsuper. As per android document it is deprecated. with your suggested code i get same error.
manifest.xml:
Mainactivity.Java
Application.java
Error:
@ClevercodeTech @h0x539 Could you maybe wrap your code into a <details> </details>
to make this thread more readable?
@ClevercodeTech @h0x539 Could you maybe wrap your code into a
<details> </details>
to make this thread more readable?
thanks for the suggestion. Updated as per your suggestion.
@ClevercodeTech
Try to make a standalone build of the android module.
Android Studio -> right click on android package -> Flutter -> Open Android module in Android Studio
Flutter Android module in Android Studio -> Terminal -> ./gradlew clean && ./gradlew build
Resolved the issue. Flutter instruction was not clear or i didn't get what they were saying. i changed the following line in the beginning of my manifest.xml:
android:name="io.flutter.app.FlutterApplication"
to
android:name=".Application"
<application
android:name="io.flutter.app.FlutterApplication"
android:name=".Application"
android:label="Mattuvandi"
android:icon="@mipmap/ic_launcher">
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="*****"/>
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".Application"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Black.NoTitleBar" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
I did it and the error is out, but it is not calling the onBackgroundMessage anymore.
Closing this issue because it looks like it's resolved.
@kalibu if you are still experiencing issues calling the onBackgroundMessage with the latest version of Flutter and FlutterFire plugin, can you please provide your updated flutter doctor -v
and your flutter run --verbose/flutter build --verbose
?
Also, to better address the issue, would be helpful
if you could post a self contained app on github
or the steps to reproduce it.
Thank you
@helenaford
This has not been resolved at all.
Hint: there has not been an update to the plugin (on Android) since I opened this issue. I only replaced one deprecated method that had nothing to do with this, so basically there has not been an update since I opened the issue..
@creativecreatorormaybenot did you try the solution provided by @ClevercodeTech ?
@helenaford That "solution" only makes the error message go away and does not fix the underlying problem (the plugin is broken on Android, see #2017 for a start; there are way more issues for background messages).
The plugin would at least need to address this somewhere. Even if the underlying problem is not fixed immediately, the README
section and more would need to be updated.
@helenaford That "solution" only makes the error message go away and does not fix the underlying problem (the plugin is broken on Android, see #2017 for a start; there are way more issues for background messages).
The plugin would at least need to address this somewhere. Even if the underlying problem is not fixed immediately, the
README
section and more would need to be updated.
Background message works for me.
you need to add a static method to capture the incoming message from firebase server. Below is a sample code
static Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async { print(message); return Future<void>.value(); }
below is the detailed code
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/material.dart';
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
class FirebaseClass {
firebaseNotification(context,topic ) {
var platform = Theme.of(context).platform;
final requestServer = RequestServer();
print("firebaseinitiated");
_firebaseMessaging.subscribeToTopic(topic);
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
},
onBackgroundMessage: platform == TargetPlatform.iOS ? null : myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
if (platform == TargetPlatform.iOS) {
_firebaseMessaging
.requestNotificationPermissions(const IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
}
_firebaseMessaging.getToken().then((String token) {
assert(token != null);
//setting fire base toke in own server this is needed to message from your server
// requestServer is a custom class to connect with my server
requestServer.requestServer("SetFirebaseToken", context).then((e) {
e == 1 ? print("Push Messaging token: $token") : print("errror sending data to server");
});
});
}
notification() async {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid = new AndroidInitializationSettings('logo');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(
initializationSettings,
);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description',
importance: Importance.Max, priority: Priority.High, ticker: 'ticker');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(0, 'plain title', 'plain body', platformChannelSpecifics,
payload: 'item x');
}
static Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
print(message);
return Future<void>.value();
}
}
@ClevercodeTech
If that works with all versions (Flutter beta + master too), then I suppose that would be a solution.
Still, the issue should remain open until this is at least integrated into the README.
@ClevercodeTech Can you provide detailed instructions?
@ClevercodeTech Can you provide detailed instructions?
Please follow the instruction as shown in the following link https://pub.dev/packages/firebase_messaging
for receiving background message. importantly you need to change your android manifest.
usually flutter application starts like this
<application
android:name="io.flutter.app.FlutterApplication"
you need to change the name to below
<application android:name=".Application" ...>
.Application refers to Application.java. Which contains below. package com.mattuvandi.user is my application. This should be changed to yours. e.g
package com.domain.application
package com.mattuvandi.user;
import android.os.Bundle;
import io.flutter.app.FlutterApplication;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
@override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
@override
public void registerWith(PluginRegistry pluginRegistry) {
FirebaseMessagingPlugin.registerWith(pluginRegistry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
}
Doesn't work for me. Tried to switch branch from stable
to master
, didn't help.
Doesn't work for me. Tried to switch branch from
stable
tomaster
, didn't help.
could you please post your code.
Sure.
// Application.kt
class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
FlutterFirebaseMessagingService.setPluginRegistrant(this);
// ...
}
override fun registerWith(registry: PluginRegistry?) {
FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
// ...
}
}
// AndroidManifest.xml
<application
android:name=".Application" // Changed from `io.flutter.app.FlutterApplication`
... />
// build.gradle under app
// ...
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.google.firebase:firebase-messaging:20.1.6'
// ...
}
have you included
// under [project]/android/app/build.gradle
apply plugin: 'com.google.gms.google-services'
Yes.
// under [project]/android/build.gradle
buildscript {
ext.kotlin_version = '1.3.72'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.3'
classpath 'com.google.gms:google-services:4.3.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
// under [project]/android/app/build.gradle
// ...
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"
@lexdevel
Not sure if this helps. But i added activity tag as below in manifest.
<activity android:name=".Application"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<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>
@ClevercodeTech, thanks, unfortunately I have pretty similar config.
@lexdevel please post your error.
@ClevercodeTech, sure, you may find output below. Reproduced when I specify onBackgroundMessage
callback in the configure
method of the FirebaseMessaging
class.
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): Failed to handle method call
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.app.Activity.getMainLooper()' on a null object reference
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at com.google.android.gms.common.api.GoogleApi.<init>(Unknown Source:50)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at com.google.android.gms.location.FusedLocationProviderClient.<init>(Unknown Source:8)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at com.google.android.gms.location.LocationServices.getFusedLocationProviderClient(Unknown Source:2)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at com.lyokone.location.FlutterLocation.setActivity(FlutterLocation.java:106)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at com.lyokone.location.LocationPlugin.registerWith(LocationPlugin.java:35)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:164)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.onMethodCall(FirebaseMessagingPlugin.java:176)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:226)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:631)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at android.os.MessageQueue.next(MessageQueue.java:336)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at android.os.Looper.loop(Looper.java:174)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at android.app.ActivityThread.main(ActivityThread.java:7356)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
E/flutter ( 5004): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'android.os.Looper android.app.Activity.getMainLooper()' on a null object reference, null)
E/flutter ( 5004): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter ( 5004): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter ( 5004): <asynchronous suspension>
E/flutter ( 5004): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
E/flutter ( 5004): #3 FirebaseMessaging.configure (package:firebase_messaging/firebase_messaging.dart:130:16)
E/flutter ( 5004): #7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4644:58)
E/flutter ( 5004): #8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4480:5)
E/flutter ( 5004): #9 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #10 Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #11 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5834:14)
E/flutter ( 5004): #12 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #13 Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #14 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4531:16)
E/flutter ( 5004): #15 Element.rebuild (package:flutter/src/widgets/framework.dart:4222:5)
E/flutter ( 5004): #16 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4485:5)
E/flutter ( 5004): #17 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4480:5)
E/flutter ( 5004): #18 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #19 Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #20 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5834:14)
E/flutter ( 5004): #21 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #22 Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #23 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5834:14)
E/flutter ( 5004): #24 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #25 Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #26 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4531:16)
E/flutter ( 5004): #27 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4679:11)
E/flutter ( 5004): #28 Element.rebuild (package:flutter/src/widgets/framework.dart:4222:5)
E/flutter ( 5004): #29 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4485:5)
E/flutter ( 5004): #30 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4670:11)
E/flutter ( 5004): #31 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4480:5)
E/flutter ( 5004): #32 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #33 Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #34 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5834:14)
E/flutter ( 5004): #35 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #36 Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #37 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5834:14)
E/flutter ( 5004): #38 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #39 Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #40 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4531:16)
E/flutter ( 5004): #41 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4679:11)
E/flutter ( 5004): #42 Element.rebuild (package:flutter/src/widgets/framework.dart:4222:5)
E/flutter ( 5004): #43 ComponentElement._firstBuild (package:flutter/src/widgets/fra
E/flutter ( 5004): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method FcmDartService#initialized on channel plugins.flutter.io/firebase_messaging_background)
E/flutter ( 5004): #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
E/flutter ( 5004): <asynchronous suspension>
E/flutter ( 5004): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
E/flutter ( 5004): #2 _fcmSetupBackgroundChannel (package:firebase_messaging/firebase_messaging.dart:50:21)
E/flutter ( 5004): #3 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:257:25)
E/flutter ( 5004): #4 _rootRun (dart:async/zone.dart:1184:13)
E/flutter ( 5004): #5 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter ( 5004): #6 _runZoned (dart:async/zone.dart:1619:10)
E/flutter ( 5004): #7 runZonedGuarded (dart:async/zone.dart:1608:12)
E/flutter ( 5004): #8 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:249:5)
E/flutter ( 5004): #9 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
E/flutter ( 5004): #10 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter ( 5004): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method FcmDartService#initialized on channel plugins.flutter.io/firebase_messaging_background)
i believe it may be due to your background message handler.
Below is my firebase class which handles background notification. Note background message handler is outside the class.
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
class FirebaseClass {
firebaseNotification(context, userInfo) {
var platform = Theme.of(context).platform;
_firebaseMessaging.subscribeToTopic(userID); //subscribe to
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
notification(message)
print("onMessage: $message"); //call Local notification here or any code you wish
},
onBackgroundMessage: platform == TargetPlatform.iOS ? null : myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
notification(message)
print("onLaunch: $message"); //call Local notification here or any code you wish
},
onResume: (Map<String, dynamic> message) async {
notification(message)
print("onResume: $message"); //call Local notification here or any code you wish
},
);
if (platform == TargetPlatform.iOS) {
_firebaseMessaging
.requestNotificationPermissions(const IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
}
_firebaseMessaging.getToken().then((String token) {
assert(token != null);
// here send the token to server
});
}
static notification(message) async {
var title = message["notification"]["title"];
var body = message["notification"]["body"];
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid = new AndroidInitializationSettings('launcher_icon');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(
initializationSettings, //onSelectNotification: onSelectNotification
);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description',
importance: Importance.Max, priority: Priority.High, ticker: 'ticker');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(0, title, body, platformChannelSpecifics, payload: 'item x');
}
}
Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
FirebaseClass.notification(message);
return Future<void>.value();
}
I moved the FirebaseMessaging
class instance and a background callback outside of the widget (like in the example you provided me with), still have an issue. Before, I followed the docs: created a static function to handle the background message.
@lexdevel make sure the name matches.
firebase config
onBackgroundMessage: platform == TargetPlatform.iOS ? null : myBackgroundMessageHandler,
Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
FirebaseClass.notification(message);
return Future<void>.value();
}
make sure myBackgroundMessageHandler is standalone not inside any class.
e.g
imports //necessary imports
class stateful widget {
//widget class
}
myBackgroundMessageHandler
Yes, double checked.
import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
class DemoPage extends StatefulWidget {
@override
_DemoPageState createState() => _DemoPageState();
}
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
debugPrint('I was here!');
return Future<void>.value();
}
class _DemoPageState extends State<DemoPage> {
@override
void initState() {
super.initState();
_firebaseMessaging.configure(
onMessage: (_) => null,
onLaunch: (_) => null,
onResume: (_) => null,
onBackgroundMessage: _onBackgroundMessage
);
}
@override
Widget build(BuildContext context) {
return Container();
}
}
I would more expect problem on native part, seems the is an error trying to register a plugin.
i didn't initiate the firebase configuration from initState(). see below my implementation. I call my firebase class from widgets. Not sure if it helps you. you can try.
bool runfirebase = true;
@override
Widget build(BuildContext context) {
final UserInfo userInfo = Provider.of<UserInfo>(context);
if (runfirebase) {
firebaseClass.firebaseNotification(context);
runfirebase = false;
}
}
That's a bit strange, to be honest, I support we should use the build
method for building widgets. However, I just tried and this didn't help.
@ClevercodeTech, I would really appreciate it if you could provide me with the versions of flutter
, firebase messaging plugin
and com.google.gms:google-services
. I hope I could downgrade them to make the background messages work.
I hope you included google-services.json in /android/app folder. also internet permission in mnifest.xml
Flutter Flutter 1.12.13+hotfix.9 dependencies: firebase_messaging: ^6.0.13
/android/build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.2'
}
/android/App/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'
dependencies {
implementation 'com.google.firebase:firebase-messaging:20.1.6'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
Thank you. Unfortunately had the same result. Regarding the json file, of course I did include it. I face the issue only for background messaging, other work fine.
@lexdevel
Not sure if this helps. But i added activity tag as below in manifest.
<activity android:name=".Application" android:launchMode="singleTop" android:theme="@android:style/Theme.Black.NoTitleBar" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <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>
@ClevercodeTech
I followed your example code but couldn't get the background message working when the app is slide away from the phone tray.
Firstly, I'm curious to ask if your app received background messages when it's not on the phone tray?
And secondly, I noticed the quoted reply has ".Application" as it's activity name. Does this mean I should use this in both the <application>
and<activity>
level?
Thanks.
@ClevercodeTech I think I found an issue: I had several plugins initialization and seems there's a conflict with Location
plugin.
override fun registerWith(registry: PluginRegistry?) {
LocationPlugin.registerWith(registry?.registrarFor("com.lyokone.location.LocationPlugin")) // Comment this line to resolve the issue
FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
SharedPreferencesPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin"))
}
Regarding the Location
, it's not necessary to call the registerWith
method for the plugin, but in my case it was required, since I used Location
in background (I came up with this solution and that helped me).
Anyway, thanks. I can confirm that I got rid of the issue.
But calling FirebaseMessagingPlugin.registerWith() really only is a workaround and not a solution.
With android embedding v2 registerWith() should not be needed anymore and is only kept as a fallback for old flutter applications.
Ideally FirebaseMessaging should be setup correctly within onAttachedToEngine() .. so that it would automatically be able to run in the background. Thats basically what android v2 embedding is all about.. That you DON'T have to write all these things anymore to make stuff like that possible.
@lazylazyllama, I understand, but the plugin DOES NOT work correctly, so as other plugins I checked. So for now I have to call registerWith
method.
@ClevercodeTech changing
from
android:name="io.flutter.app.FlutterApplication"
to
android:name=".Application"
to resolved my issue
The POINT is:
if:
android:name="xxx.xxx.xxx.YourApplication"
then you need to put FlutterFirebaseMessagingService.setPluginRegistrant(this);
to xxx.xxx.xxx.YourApplication's onCreate
and
override fun registerWith(registry: PluginRegistry?)
same.
@ClevercodeTech I think I found an issue: I had several plugins initialization and seems there's a conflict with
Location
plugin.override fun registerWith(registry: PluginRegistry?) { LocationPlugin.registerWith(registry?.registrarFor("com.lyokone.location.LocationPlugin")) // Comment this line to resolve the issue FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")) SharedPreferencesPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin")) }
Regarding the
Location
, it's not necessary to call theregisterWith
method for the plugin, but in my case it was required, since I usedLocation
in background (I came up with this solution and that helped me).Anyway, thanks. I can confirm that I got rid of the issue.
Can you please, for the love of all Flutter and the buggyness of this issue.
Please post your implementation. There is not enough success with Kotlin trying to use this package.
@bretie
If you are using multiple plugin use the following implementation in your MainActivity java
package com.yourdomain.appname; // change it appropriately
import android.os.Bundle;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void configureFlutterEngine(@NonNull final FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
}
}
Application.java
package com.yourdomain.appname; // change it appropriately
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
@Override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
@Override
public void registerWith(PluginRegistry registry) {
FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
}
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package=" com.yourdomain.appname">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:name=".Application"
Hope it solves your issue.
@bretie
If you are using multiple plugin use the following implementation in your MainActivity java
package com.yourdomain.appname; // change it appropriately import android.os.Bundle; import androidx.annotation.NonNull; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void configureFlutterEngine(@NonNull final FlutterEngine flutterEngine) { GeneratedPluginRegistrant.registerWith(flutterEngine); } }
Application.java
package com.yourdomain.appname; // change it appropriately import io.flutter.app.FlutterApplication; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback; import io.flutter.plugins.GeneratedPluginRegistrant; import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService; import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin; public class Application extends FlutterApplication implements PluginRegistrantCallback { @Override public void onCreate() { super.onCreate(); FlutterFirebaseMessagingService.setPluginRegistrant(this); } @Override public void registerWith(PluginRegistry registry) { FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")); } }
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package=" com.yourdomain.appname"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:name=".Application"
Hope it solves your issue.
I need it in Kotlin, I'm not using Java for my android app. Is there any way to port this over?
@bretie
My suggestion don’t spend so much time solving a problem in same way. Try trial and error.
Anyways,
You have two options.
One: if you don’t have any other codes in kotlin. Just use this implementation it should work.
Two: use IntelliJ in android studio to convert this to kotlin.
@bretie, Kotlin worked for me. The procedure is the following:
android/app/build.gradle
file:
// At the bottom of the file, you will find a `dependencies` section
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
// Required for firebase messaging
implementation 'com.google.firebase:firebase-messaging:20.1.6'
}
2. Create an `Application` class
```kotlin
package YOUR_PACKAGE_NAME
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
override fun registerWith(registry: PluginRegistry?) {
FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
}
}
AndroidManifest.xml
improve the application
tag:
<!-- FROM -->
<application android:name="io.flutter.app.FlutterApplication" ... />
<application android:name=".Application" ... />
4. In the `dart` code make sure the `onBackgroundMessage` callback is static or out of class function.
```dart
Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
debugPrint('On background message $message');
return Future<void>.value();
}
class _WhateverState extends State<Whatever> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
@override
void initState() {
super.initState();
_firebaseMessaging.configure(
onBackgroundMessage: _onBackgroundMessage,
// ...
);
}
}
@bretie, also I got rid of the Location plugin and switched to the Geolocator plugin. That worked fine.
In my case the problem was caused by KeyboardVisibility plugin. Removing it has solved it.
In my case the problem was caused by KeyboardVisibility plugin. Removing it has solved it.
You gave me the solution: Removing the flutter_keyboard_visibility worked for me.
import android.os.Bundle;
import androidx.annotation.NonNull; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }
@Override public void configureFlutterEngine(@NonNull final FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
}}
Helllo. Thanks for helping.
I tried everything It`s all red here.
RED -> import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService; RED -> import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
RED -> FlutterFirebaseMessagingService.setPluginRegistrant(this);
@bretie, Kotlin worked for me. The procedure is the following:
- Improve
android/app/build.gradle
file:// At the bottom of the file, you will find a `dependencies` section dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" // Required for firebase messaging implementation 'com.google.firebase:firebase-messaging:20.1.6' }
- Create an
Application
classpackage YOUR_PACKAGE_NAME import io.flutter.app.FlutterApplication import io.flutter.plugin.common.PluginRegistry import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback { override fun onCreate() { super.onCreate() FlutterFirebaseMessagingService.setPluginRegistrant(this); } override fun registerWith(registry: PluginRegistry?) { FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")) } }
- In
AndroidManifest.xml
improve theapplication
tag:<!-- FROM --> <application android:name="io.flutter.app.FlutterApplication" ... /> <!-- TO --> <application android:name=".Application" ... />
- In the
dart
code make sure theonBackgroundMessage
callback is static or out of class function.Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async { debugPrint('On background message $message'); return Future<void>.value(); } class _WhateverState extends State<Whatever> { final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); @override void initState() { super.initState(); _firebaseMessaging.configure( onBackgroundMessage: _onBackgroundMessage, // ... ); } }
Thanks so much you save my life
This is caused by:
This happens on Android when running a Flutter app built with
firebase_messaging: 6.0.9
andFlutter 1.15.4-pre.199
.This also happens every time calling
FirebaseMessaging.configure
in the Flutter app when running on Android: