Flutterfire: firebase-messaging: Android Integration

Created on 8 Sep 2019  ·  39Comments  ·  Source: FirebaseExtended/flutterfire

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!.

bug

Most helpful comment

@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.

All 39 comments

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?
Screen Shot 2019-09-11 at 10 32 52 AM

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 myBackgroundMessageHandler(Map message) {
print('received notification in BG');
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.

}

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.yamlwith 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.

@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"
        }
      },

I have a similar condition: my firebase project id is "pais-e-filhos" and it serves 2 apps: paiefilhopai and paiefilhofilho. All the environment is online and in production. Now, I need to implement FCM. How I can configure my apps to be served with only one Firebase project (with "-" in them name). I can´t rename none of them.

Thanks.

@markuspaschi no it did not work I still have firebasemessaging & FlutterFirebaseMessagingService not resolved.

how you resolve it?

@markuspaschi no it did not work I still have firebasemessaging & FlutterFirebaseMessagingService not resolved.

how you resolve it?

Not solved iet...

@htsnet have you taken a look at https://github.com/FirebaseExtended/flutterfire/issues/199#issuecomment-534534251 ?

After hours of searching, this complete comment helps me to successfully implement the new FCM version - I give you that the documentation needs to be deepen further.

Hi @srsandy
I see there's an open issue addressing the bug
and the issue referenced here (thank you @aleaforny ) about the documentation.

I'm closing the current one as duplicate.
If you disagree please write in the comments
and I will reopen it.
Thank you

  1. i can't change my firebase project id
  2. i can't change pubspec.yml: name to make it the same name as firebase project id. because my firebase project name have underscore. like project-name, and dart not accept name like that.

My app still crush on first time start

any other solution please?

this was the final prob with me when changes my name in pubspec.yamlwith 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

i can't change my firebase project id
i can't change pubspec.yml: name to make it the same name as firebase project id. because my firebase project name have underscore. like project-name, and dart not accept name like that.
any other solution please?

for me decided by doing this:

Aplication.kt

package br.gov.rj.riodasostras.appsescverao

import android.os.Bundle

import io.flutter.app.FlutterActivity
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 com.google.firebase.messaging.FirebaseMessagingService

 class Application : FlutterApplication() , PluginRegistrantCallback {

   override fun onCreate() {
     super.onCreate();
     FlutterFirebaseMessagingService.setPluginRegistrant(this);
   }

   override fun registerWith( registry: PluginRegistry) {
     GeneratedPluginRegistrant.registerWith(registry);
   }
 }

android/build.gradle


buildscript {
    ext.kotlin_version = '1.3.0' //1.2.71
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1' //3.2.1 //3.5.3
        classpath 'com.google.gms:google-services:4.3.3' //4.3.2
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

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 plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
//inicio alteração
apply plugin: 'com.google.gms.google-services'
//fim

//importa arquivo de configuração da chave de assinatura do App
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}


android {
    compileSdkVersion 28

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

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "br.gov.rj.riodasostras.appsescverao"
        minSdkVersion 21
        multiDexEnabled true
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    //sign release
    signingConfigs {
        release {
            keyAlias localProperties['keyAlias']
            keyPassword localProperties['keyPassword']
            storeFile file(localProperties['storeFile'])
            storePassword localProperties['storePassword']
        }
    }

    buildTypes {
        release {
            // Signing with the debug keys for now, so `flutter run --release` works.
            //signingConfig signingConfigs.debug
            //abilita a versão assinada para publicação na Play store
            signingConfig signingConfigs.release
            //abilita obfuscação e mimificação
            minifyEnabled true
            useProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
}

flutter {
    source '../..'
}

dependencies {
    //inicio alteração para abilita multidex e firebase
    implementation 'com.android.support:multidex:2.0.0' //1.0.3
    implementation 'com.google.firebase:firebase-core:17.2.1'
    implementation "com.google.firebase:firebase-analytics:17.2.1" 
    implementation "com.google.firebase:firebase-messaging:20.1.0"
    //fim
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    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'
}

//inicio alteração
apply plugin: 'com.google.gms.google-services'
//fim

pubspec.yaml

name: appsescverao
description: Aplicativo do Sesc Verão Rio das Ostras

version: 2.0.0+2

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

  cupertino_icons: ^0.1.3
  http: ^0.12.0+2
  path_provider: ^1.5.1
  flutter_advanced_networkimage: ^0.6.2
  sqflite: ^1.2.0
  connectivity: ^0.4.6+1
  url_launcher: ^5.4.1
  cloud_firestore: ^0.13.0+1
  firebase_auth: ^0.15.2
  google_sign_in: ^4.1.0
  firebase_database: ^3.1.1
  rxdart: ^0.23.1
  webview_flutter: ^0.3.18+1
  auto_size_text: ^2.1.0
  flutter_map: ^0.8.0
  latlong: ^0.6.1
  queries: ^0.1.12
  firebase_analytics: ^5.0.9
  shared_preferences: ^0.5.6
  share: ^0.6.3+5
  map_launcher: ^0.3.2
  #audioplayers: ^0.13.5
  #audio_streams: ^1.0.0+2
  firebase_messaging: ^6.0.9

dev_dependencies:
  flutter_test:
    sdk: flutter

  intl_translation: ^0.17.7

flutter:

  uses-material-design: true

  assets:
    - assets/logo.png
    - assets/background.png
    - assets/background2.png
    - assets/background3.png
    - assets/user-avatar.png
    - assets/logo-pmro-cinza.png
    - assets/logo-pmro-branco.png
    - assets/wave-bottom.png
    - assets/wave-top.png
    - assets/logo2.png
    - assets/logo-branca.png

  fonts:
    - family: Big Noodle Titling
      fonts:
        - asset: fonts/big_noodle_titling.ttf
    - family: GlosaDisplayW01-Bold
      fonts:
        - asset: fonts/glosa_display_w01_bold.ttf
    - family: BakerieSmoothCondensedMedium
      fonts:
        - asset: fonts/BakerieSmoothCondensed-Medium.otf
    - family: BakerieSmoothBold
      fonts:
        - asset: fonts/BakerieSmooth-Bold.otf
    - family: iconsmind
      fonts:
        - asset: fonts/iconsmind.ttf

don't forget to remove

@Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { GeneratedPluginRegistrant.registerWith(flutterEngine);

from the mainactivity file under the android folder. If not, you will get an error.

Could everyone who still has this problem please file a new issue with the exact descriptions what happens, logs and the output of 'flutter doctor -v' please.
All system setups can be slightly different so it's always better to open new issues and reference related issues.

I had similar issue and I had to write Application.kt like this:

Note: After this reinstall app on mobile device

package xxx.yyyyyyyy.app

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"))
    }
}

@fehimdervisbegovic this seem the only it worked with me as well. I don't know why the docs don't have an example on how to setup it properly for Kotlin projects.

I had similar issue and I had to write Application.kt like this:

Note: After this reinstall app on mobile device

package xxx.yyyyyyyy.app

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"))
    }
}

@fehimdervisbegovic does this require the .app at the end of package xxx.yyyyyyyy.app ??

@fehimdervisbegovic or @miguelpruivo, do you have an working example you could share?
I still get following error when I run the app:

E/flutter ( 4306): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, PluginRegistrantCallback is not set., null)

for me decided by doing this:

Aplication.kt

package br.gov.rj.riodasostras.appsescverao

import android.os.Bundle

import io.flutter.app.FlutterActivity
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 com.google.firebase.messaging.FirebaseMessagingService

 class Application : FlutterApplication() , PluginRegistrantCallback {

   override fun onCreate() {
     super.onCreate();
     FlutterFirebaseMessagingService.setPluginRegistrant(this);
   }

   override fun registerWith( registry: PluginRegistry) {
     GeneratedPluginRegistrant.registerWith(registry);
   }
 }

android/build.gradle

buildscript {
    ext.kotlin_version = '1.3.0' //1.2.71
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1' //3.2.1 //3.5.3
        classpath 'com.google.gms:google-services:4.3.3' //4.3.2
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

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 plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
//inicio alteração
apply plugin: 'com.google.gms.google-services'
//fim

//importa arquivo de configuração da chave de assinatura do App
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}


android {
    compileSdkVersion 28

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

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "br.gov.rj.riodasostras.appsescverao"
        minSdkVersion 21
        multiDexEnabled true
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    //sign release
    signingConfigs {
        release {
            keyAlias localProperties['keyAlias']
            keyPassword localProperties['keyPassword']
            storeFile file(localProperties['storeFile'])
            storePassword localProperties['storePassword']
        }
    }

    buildTypes {
        release {
            // Signing with the debug keys for now, so `flutter run --release` works.
            //signingConfig signingConfigs.debug
            //abilita a versão assinada para publicação na Play store
            signingConfig signingConfigs.release
            //abilita obfuscação e mimificação
            minifyEnabled true
            useProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
}

flutter {
    source '../..'
}

dependencies {
    //inicio alteração para abilita multidex e firebase
    implementation 'com.android.support:multidex:2.0.0' //1.0.3
    implementation 'com.google.firebase:firebase-core:17.2.1'
    implementation "com.google.firebase:firebase-analytics:17.2.1" 
    implementation "com.google.firebase:firebase-messaging:20.1.0"
    //fim
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    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'
}

//inicio alteração
apply plugin: 'com.google.gms.google-services'
//fim

pubspec.yaml

name: appsescverao
description: Aplicativo do Sesc Verão Rio das Ostras

version: 2.0.0+2

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

  cupertino_icons: ^0.1.3
  http: ^0.12.0+2
  path_provider: ^1.5.1
  flutter_advanced_networkimage: ^0.6.2
  sqflite: ^1.2.0
  connectivity: ^0.4.6+1
  url_launcher: ^5.4.1
  cloud_firestore: ^0.13.0+1
  firebase_auth: ^0.15.2
  google_sign_in: ^4.1.0
  firebase_database: ^3.1.1
  rxdart: ^0.23.1
  webview_flutter: ^0.3.18+1
  auto_size_text: ^2.1.0
  flutter_map: ^0.8.0
  latlong: ^0.6.1
  queries: ^0.1.12
  firebase_analytics: ^5.0.9
  shared_preferences: ^0.5.6
  share: ^0.6.3+5
  map_launcher: ^0.3.2
  #audioplayers: ^0.13.5
  #audio_streams: ^1.0.0+2
  firebase_messaging: ^6.0.9

dev_dependencies:
  flutter_test:
    sdk: flutter

  intl_translation: ^0.17.7

flutter:

  uses-material-design: true

  assets:
    - assets/logo.png
    - assets/background.png
    - assets/background2.png
    - assets/background3.png
    - assets/user-avatar.png
    - assets/logo-pmro-cinza.png
    - assets/logo-pmro-branco.png
    - assets/wave-bottom.png
    - assets/wave-top.png
    - assets/logo2.png
    - assets/logo-branca.png

  fonts:
    - family: Big Noodle Titling
      fonts:
        - asset: fonts/big_noodle_titling.ttf
    - family: GlosaDisplayW01-Bold
      fonts:
        - asset: fonts/glosa_display_w01_bold.ttf
    - family: BakerieSmoothCondensedMedium
      fonts:
        - asset: fonts/BakerieSmoothCondensed-Medium.otf
    - family: BakerieSmoothBold
      fonts:
        - asset: fonts/BakerieSmooth-Bold.otf
    - family: iconsmind
      fonts:
        - asset: fonts/iconsmind.ttf

@insinfo Can you add AndroidManifest.xml too?

@akilawickey thanks for sharing.
I manage to get it to work yesterday. will upload a repo soon with the example

I have error:
Unresolved reference: setPluginRegistrant

@akilawickey thanks for sharing.
I manage to get it to work yesterday. will upload a repo soon with the example

Did you ever upload that repo?

@akilawickey thanks for sharing.
I manage to get it to work yesterday. will upload a repo soon with the example

Did you ever upload that repo?

androidapp\src\main\kotlin\Application.kt

package information.app

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

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

  override fun registerWith(registry: PluginRegistry) {
    FirebaseCloudMessagingPluginRegistrant.registerWith(registry)
  }
}

androidapp\src\main\kotlin\FirebaseCloudMessagingPluginRegistrant.kt

package information.app

import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin

class FirebaseCloudMessagingPluginRegistrant {
  companion object {
    fun registerWith(registry: PluginRegistry) {
      if (alreadyRegisteredWith(registry)) {
        return;
      }
      FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }

    fun alreadyRegisteredWith(registry: PluginRegistry): Boolean {
      val key = FirebaseCloudMessagingPluginRegistrant::class.java.name
      if (registry.hasPlugin(key)) {
        return true
      }
      registry.registrarFor(key)
      return false
    }
  }
}

pubspec.yaml

environment:
  sdk: ">=2.2.2 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  path_provider:
  path:
  http:

  cloud_firestore: 
  firebase_analytics: 
  firebase_core: 
  firebase_auth: 
  firebase_messaging:
  firebase_crashlytics:

android\build.gradle

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
        maven {
            url 'https://maven.fabric.io/public'
        }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'io.fabric.tools:gradle:1.26.1'
        classpath 'com.google.gms:google-services:4.3.3'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

androidapp\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 = '11'
}

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

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

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 28

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

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "information.app"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-analytics:17.2.1'
    implementation "com.google.firebase:firebase-messaging:20.1.0"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric'
Was this page helpful?
0 / 5 - 0 ratings