firebase-messaging: Android Integration
Android Integration
I'm not an android developer. I'm trying to use FCM with flutter
Using firebase_messaging: ^5.1.5
In android integrations, there is a section Optionally handle background messages Step 1 says Add an Application.java class to your app I'm confused wherein the app.
- inside the app folder
- inside the app/main
- inside android/
I tried adding it to all the places but my application crashes. No console errors but not able to run the application.
I have this exact code in my Application.java
package io.flutter.plugins.firebasemessagingexample;
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;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
@Override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
@Override
public void registerWith(PluginRegistry registry) {
GeneratedPluginRegistrant.registerWith(registry);
}
}
also I have updated AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.venuemonk.agent_notify">
<!-- 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=".Application"
android:label="agent_notify"
android:icon="@mipmap/ic_launcher">
<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">
<!-- This keeps the window background of the activity showing
until Flutter renders its first frame. It can be removed if
there is no splash screen (such as the default splash screen
defined in @style/LaunchTheme). -->
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<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>
</application>
</manifest>
Also, I get error's like firebasemessaging & firebasemessagingexample not resolved.
Improvements If possible pls explicitly method where should be added.
Thank You in adv!.
Hey srsandy,
you need to add the Application.java file in the same folder, where your MainActivity is.
It should be located under:
android/app/src/main/.../com/venuemonk/agent_notify/Application.java
Then you have to modify that class according to your package name, which is:
com.venuemonk.agent_notify.
So the first line of the file should be:
package com.venuemonk.agent_notify;
Let me know if it worked :)
My app also crashed. I'm already following every step. Please update firebase_messaging example for this background implementation. Thank you :)
Logs
I/flutter (22742): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (22742): The following NoSuchMethodError was thrown attaching to the render tree:
I/flutter (22742): The method 'toRawHandle' was called on null.
I/flutter (22742): Receiver: null
I/flutter (22742): Tried calling: toRawHandle()
I/flutter (22742):
I/flutter (22742): When the exception was thrown, this was the stack:
I/flutter (22742): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5)
I/flutter (22742): #1 FirebaseMessaging.configure (package:firebase_messaging/firebase_messaging.dart:122:55)
@markuspaschi no it did not work I still have firebasemessaging & FlutterFirebaseMessagingService not resolved.
Have you imported the FIrebaseMessaging library successfully via pubspec.yaml?
Can you tell me if you have these lines in your GeneratedPluginRegistrant.java file, located under: android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
Then you should not have any problems resolving 🤔 Which version of FIrebaseMessaging are you using and have you migrated to AndroidX?
@markuspaschi
pubspec.yaml
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
shared_preferences: ^0.5.3+4
http: ^0.12.0+2
firebase_messaging: ^5.1.5
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
I have this in my android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
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 GradleException("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 from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 28
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.venuemonk.agent_notify"
minSdkVersion 16
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
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 {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'
now when i run the app.. this is what i get
Launching lib/main.dart on Android SDK built for x86 64 in debug mode...
Initializing gradle...
Resolving dependencies...
Running Gradle task 'assembleDebug'...
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:processDebugGoogleServices'.
> No matching client found for package name 'com.venuemonk.agent_notify'
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 2s
Finished with error: Gradle task assembleDebug failed with exit code 1
You need a valid google-services.json file.
Using the Firebase Console, add an Android app to your project: Follow the assistant, download the generated google-services.json file and place it inside android/app
https://stackoverflow.com/questions/34990479/no-matching-client-found-for-package-name-google-analytics-multiple-productf?answertab=votes#tab-top
Thanks, @markuspaschi for all your help. I did add google-services.json the problem was that I had different project name in firebase console and my package name was diff.
Solved it.
I don't was to close the issue I have a request from maintainers to update the docs.
@srsandy I got the same problem "The method 'toRawHandle' was called on null" when using "onBackgroundMessage". About google-services.json and AndroidManifest.xml I put the same package name. So I'm really confused about the location of "Application.java". Where did you put that and what "package ...." line?
Can you check my case here?

Thanks in adv any helps!.
@trieuvi your Application.java is correct.
ok wait..
check your google-services.json project_info: {project_id: "abc"} should be the same as your the name: abc in pubspec.yaml file. Then the name in pubspec.yaml will become your package name.
@trieuvi
toRawHandle' was called on null
This happens, if the isolate is not found.
You need an top-level function with the name "myBackgroundMessageHandler". To do this, add the function in your main.dart:
Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
if (message.containsKey('data')) {
// Handle data message
final dynamic data = message['data'];
}
if (message.containsKey('notification')) {
// Handle notification message
final dynamic notification = message['notification'];
}
// Or do other work.
}
`
@srsandy In my google-services.json:
"project_info": {"project_id": "s-t-n"}
In my pubspec.yaml:
name: STN
I can't change name in pubspec.yalm because of Dart validation, do I have to change "project_id" as name in pubspec? About the package name you mentioned, where is that? google-services.json (client > client_info > android_client_info > package_name) or AndroidManifest.xml > package ?
@markuspaschi I got the error with this:
`Future
if (message.containsKey('notification')) {
// Handle notification message
final dynamic notification = message['notification'];
}
// Or do other work.
}
void firebaseCloudMessaging_Listeners() { if (Platform.isIOS) iOS_Permission();
_firebaseMessaging.getToken().then((token){
if (token != null && token.length > 0) {
Device _device = widget.device;
_device.token = token;
postDeviceToken(http.Client(), _device);
}
});
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('onMessage');
},
onBackgroundMessage: myBackgroundMessageHandler,
onResume: (Map<String, dynamic> message) async {
print('onResume');
},
onLaunch: (Map<String, dynamic> message) async {
print('onLaunch');
},
);
}`
Can you check any wrong here? (this code is in main.dart)
@trieuvi keep google-services.json "project_info": {"project_id": "s-t-n"} and name in pubspec.yaml same..
if you will change the project_info.project_info then u will have to changes with package_name in the same file better you change pubspec.yaml
{
"client_info": {
"mobilesdk_app_id": "1:818422264642:android:0317e0b4912871f2",
"android_client_info": {
"package_name": "com.example.abc"
}
},
@srsandy Sorry I don't understand this point:
keep google-services.json "project_info": {"project_id": "s-t-n"} and name in pubspec.yaml same..
My "package_name": "com.example.stn_app", same as package in AndroidManifest. In my case what should I change?
this was the final prob with me when changes my name in pubspec.yaml with project_info.project_id it worked.. try it once.
after changing the name in pubspec.yaml file just do packages get and re run the app
How should I configure Application.java if my android default language is kotlin?
@OliverWangWei
I wrote this in the MainActivity.kt file:
class MainActivity: FlutterActivity(), PluginRegistry.PluginRegistrantCallback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
override fun registerWith(registry: PluginRegistry?) {
GeneratedPluginRegistrant.registerWith(registry)
}
}
@lynrin Do I need to import any code like the version of java and remove the original code in MainActivity.kt?
@OliverWangWei Sorry...
It was a mistake to edit the MainActivity.kr file.
I created a new Application.kr file and wrote it as follows:
package io.flutter.plugins.firebasemessagingexample;
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
override fun registerWith(registry: PluginRegistry?) {
GeneratedPluginRegistrant.registerWith(registry);
}
}
Then proceed to Step 2 of Optionally handle background messages.
When I rewritten AndroidManifest.xml to run it from newly added Application.kr, it worked.
@lynrin Thanks a lot, it works! However, I had an issue like #125 and #144 when I added the top level myBackgroundMessageHandler function in my code.
Was https://github.com/FirebaseExtended/flutterfire/issues/111#issuecomment-530574314 resolved?
For example, we have a project on firebase called "Digital Merchant" which makes the projectId = "digital-merchant", however in the pubspec the character "-" is not supported only "_" are supported so our pubspec will never match the google services file, please note we cannot just change the name of the project on firebase there is no option and our entire pipeline etc. is built around it, so I am hoping the answer is not to "simply change the name" as that is not a solution.