firebase / flutterfire

πŸ”₯ A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.46k stars 3.91k forks source link

[firebase_messaging] Android v2 embedding crashes #1754

Closed cranst0n closed 3 years ago

cranst0n commented 4 years ago

Describe the bug Since updating my app to the Android v2 embedding I've been getting reports in Crashlytics concerning ensureInitializationComplete must be called after startInitialization io.flutter.embedding.engine.loader.FlutterLoader.ensureInitializationComplete.

The Flutter 1.12 upgrade guide says to remove all references to the startInitialization or ensureInitializationComplete methods but I see 2 references to these methods: here and here.

To Reproduce Steps to reproduce the behavior:

  1. Upgrade app to v2 embedding.
  2. Start app and then close it.
  3. Send notification from the Firebase Notification Composer.
  4. Notice app crash notification on device.
  5. See error or incorrect behavior

I have not seen the issue when I leave the app open and send the notification.

Expected behavior Notification displayed normally while app is closed.

Additional context Here is what the Crashlytics report looks like:

Fatal Exception: java.lang.RuntimeException
Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.IllegalStateException: ensureInitializationComplete must be called after startInitialization
android.app.ActivityThread.handleCreateService (ActivityThread.java:3746)
android.app.ActivityThread.access$1400 (ActivityThread.java:235)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1784)
android.os.Handler.dispatchMessage (Handler.java:106)
android.os.Looper.loop (Looper.java:214)
android.app.ActivityThread.main (ActivityThread.java:6986)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1445)

Caused by java.lang.IllegalStateException
ensureInitializationComplete must be called after startInitialization
io.flutter.embedding.engine.loader.FlutterLoader.ensureInitializationComplete (FlutterLoader.java:153)
io.flutter.view.FlutterMain.ensureInitializationComplete (FlutterMain.java:80)
io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.onCreate (FlutterFirebaseMessagingService.java:71)
android.app.ActivityThread.handleCreateService (ActivityThread.java:3734)
android.app.ActivityThread.access$1400 (ActivityThread.java:235)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1784)
android.os.Handler.dispatchMessage (Handler.java:106)
android.os.Looper.loop (Looper.java:214)
android.app.ActivityThread.main (ActivityThread.java:6986)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1445)
cranst0n commented 4 years ago

Closing this. Seems that I had left android:name="io.flutter.app.FlutterApplication" out of my <application> definition in AndroidManifest.xml.

philipgiuliani commented 4 years ago

I have the exact same issue. The app crashes when I receive a notification while the app is closed, but I get the notification when the app is running. I migrated the app using the upgrade guide.

I tried adding android:name="io.flutter.app.FlutterApplication" and it didnt help. The guide actually tells you to remove it.

carmas123 commented 4 years ago

Please reopen the issue because the problem still remain

W2YAdmin commented 4 years ago

Please reopen the issue I am facing the same thing as well!

cranst0n commented 4 years ago

Reopened. Should not have closed it.

DavidKuennen commented 4 years ago

Anyone with a solution for this? Having the same problem.

barees63 commented 4 years ago

I'm seeing this also

davcrash commented 4 years ago

I have the same problem

ryanheise commented 4 years ago

The bug happens because the plugin still calling FlutterMain.ensureInitializationComplete which it shouldn't do with the new v2 embedding. The 1.12 migration guide says:

If you invoke FlutterMain.startInitialization(...) or FlutterMain.ensureInitializationComplete(...) anywhere in your code, you should remove those calls. Flutter now initializes itself at the appropriate time.

So the "ensureInitializationComplete must be called after startInitialization" error happens because the plugin is calling ensureInitializedComplete when under v2, startInitialization is never called.

Until this is fixed, you can get around the error by making your app use the old io.flutter.app.FlutterApplication class as your application class, or if you have your own custom application class, you can either make it extend FlutterApplication or you can just call startInitialization in your own application class's onStart (which is what FlutterApplication basically does.)

miniskulljob commented 4 years ago

I'm having this issue too, unfortunately I can't go back and revert the v2 embedding implementation in my app because other plugins depend on it to work properly.

Any chance to fix this soon? This issue is quite old now...

ivanchaukn commented 4 years ago

I'm having the same issue too! Can we get it fixed soon?

ryanbliss commented 4 years ago

Having the same issue and it is impacting a large percentage of our users. Would appreciate a speedy fix :)

mnorhamizan commented 4 years ago

I'm having this issue as well

ryanheise commented 4 years ago

You may as well try the workaround I described in my post above. Just to clarify, this workaround does NOT require you to revert your project to pre-v2.

mnorhamizan commented 4 years ago

@ryanheise How about those in GeneratedPluginRegistrants? Some of my package use those do I need to include that in MainActivity.kt?

Boehrsi commented 4 years ago

Is there any information in regards to a release with a fix for this issues? Right now it's crashing always, as soon as the app isn't running at all (so e.g. killed by the system or swiped out of the app switcher). So the user will get crash dialogs over and over, for every push message he receives. This is something highly critical and would block any production release of an app (IMHO). Workarounds are something we can do during testing etc., but as I'm developing a quite complex app, with different native interactions, it would be great to have a stable backbone for the push logic and setup.

Btw. thanks for the nice plugins and all the efforts integrating Flutter into the existing Firebase world. Looking forward to more nice Flutter integrations. πŸ‘

Boehrsi commented 4 years ago

Issues related to this problem (it seems that general parts are missing for the Android v2 embedding: setup call adjustments, documentation and some internal handling e.g. for plugin calls in the onBackgroundMessage method):

Only did a really short search, so probably there are more related issues. Just wanted to show that this problem is probably affecting a larger number of developers and users than visible in this particular ticket.

MichaelM97 commented 4 years ago

Why is this not labelled severe? This causes crash dialogs to show periodically when the application is closed, which would cause most users to either disable permissions or just delete the app. This surely should be made a priority, considering that as more and more apps/packages make the move to the v2 embedding this will affect every Android user.

themisir commented 4 years ago

I don't know how but I solved it mysteriously. 🧐

robert-virkus commented 4 years ago

2510 also seems to be related. Please - PRETTY PLEASE make this is a priority.

robert-virkus commented 4 years ago

2468 also seems to be related.

mootw commented 4 years ago

I was able to fix this issue when pressing on notifications by doing this, but please read the entire post before continuing.

This is what fixed the issue for me: Add this to the application tag: android:name="io.flutter.app.FlutterApplication"

Here is my application tag

<application
        android:name="io.flutter.app.FlutterApplication"
        tools:replace="android:label"
        android:label="App Name"
        android:icon="@mipmap/ic_launcher">

My primary activity for the app is this

<activity
            android:name="io.flutter.embedding.android.FlutterActivity"
            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">

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <!--FIREBASE CLOUD MESSAGING-->
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

I also included these tags under application, among other various widgets.

<meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />

I sent a notification through a notification channel "test_channel" using the firebase console and the app did not crash when I pressed the notification; it properly entered the app. I did not test if data was received properly, but I would assume it works because it no longer crashes.

https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects This upgrade guide indicates to remove android:name="io.flutter.app.FlutterApplication" from the application tag. Adding it back in seems to fix the firebase bug, but it seems like it still functions fine with it added back in, even using v2 embedding. It seems to be working fine with all of my V2 plugins and background_fetch also is working fine as far as I can tell. This could be a temporary fix until the issue is addressed properly?

Please do test it out for yourself because this goes against the update guidelines which tell you to remove this.

estevez-dev commented 4 years ago

Hi @MooNag I have this fix in production for weeks and my users are happy. So I'm assuming it is safe.

MichaelM97 commented 4 years ago

@MooNag This just reverts one of the steps required to update to Android v2 embedding. This fix won't work for those who require the new v2 embedding and want to receive notifications.

mootw commented 4 years ago

@MichaelM97 Yeah I am aware. I said that, but it is compatible with the V2 embedding, and plugin setup, as well as fixing the crashes with FCM. It is a fix, not the correct solution to the problem, until the issue can be patched on either Flutter's end, or on the plugin side of things. Note that I am still using the v2 embedding in my project and notifications are working.

Does this fix not work for you? It would be good to note compatibility issues if they exist.

Zazo032 commented 4 years ago

@helenaford this issue is blocking us to release, is there any workaround that can prevent our app to crash when receiving a notification when our app is closed?

estevez-dev commented 4 years ago

Yes @Zazo032 , the workaround is described several times in previous comments.

Boehrsi commented 4 years ago

@MooNag @estevez-dev am I assuming right that both of you aren't using the onBackgroundMessage callback of the configure method (https://pub.dev/documentation/firebase_messaging/latest/firebase_messaging/FirebaseMessaging/configure.html)? Without the callback everything looks okay during start, but as soon the callback is added the workaround breaks (firebase_messaging: ^6.0.15 is used).

As required parts are missing for the real v2 embedding the following exception is thrown:

E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133): Failed to handle method call
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133): java.lang.RuntimeException: PluginRegistrantCallback is not set.
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:157)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.onMethodCall(FirebaseMessagingPlugin.java:176)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:226)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:631)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at android.os.MessageQueue.next(MessageQueue.java:326)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at android.os.Looper.loop(Looper.java:160)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at android.app.ActivityThread.main(ActivityThread.java:6669)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 7133):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Btw. thanks for the efforts to workaround this problem @MooNag !

Edit: Already tried to implement my own class extending io.flutter.app.FlutterApplication and doing the registration for the background stuff there. Result: not stable / not working

estevez-dev commented 4 years ago

Hey @Boehrsi, you are right, I'm not using background messages handling.

Boehrsi commented 4 years ago

@FirebaseExtended/invertase at first thanks for taking over the FirebaseExtended maintenance (via https://github.com/FirebaseExtended/flutterfire/issues/2582). πŸ‘ At second and as mentioned in the issue, if we have some important issues in mind we should ping you. This comment is more or less exactly this.

Even though FCM and the cloud messaging part isn't your highest priority, it would be awesome to have full fledged push support in Flutter, even if the app isn't running at all. Without comprehensive push support neither chat apps, nor mail apps or other user interaction heavy apps can be realized completely. I selected this specific issue, but I also linked interconnected ones (https://github.com/FirebaseExtended/flutterfire/issues/1754#issuecomment-621164872) and there are probably more. It's about both the actual functionality and also the documentation part.

If there is anything that can be done by me / us please just respond, as I would happily provide use cases, actual problems or a more comprehensive error description if helpful. If possible I would also like to contribute to the problem itself, but right now I don't think that trail / error approaches in such a core component of an ecosystem would be helpful.

Boehrsi commented 3 years ago

Probably also related to this topic (general v2 embedding problems): https://github.com/FirebaseExtended/flutterfire/issues/2111 (embedding v2 + data message, but the app is not even killed, it's just in the background. Is not crashing, but not working nevertheless).

cfchris commented 3 years ago

So that developers have more information:

(Android Flutter Update Challenges)

We have an application that we started on Flutter 1.7(ish). We were on (v1.12.13+hotfix.8) when 1.17.X came out. We waited until we had released a big batch of features before updating Flutter. We released the features. Waited a week. All good. So, I decided to update Flutter/Dart (and all of our dependencies).

When I got to updating barcode_scan, I read through the change log and followed all update instructions. The barcode_scan upgrade instructions linked to the Flutter Upgrading pre 1.12 Android projects instructions. So, I followed those.

Later I got down to firebase_messaging. I updated to the most current of that too (^6.0.16). After updating, I thought everything was working until I closed the app (swiped out of open app list) and sent a notification. I got an app crash notification. I tried reverting to the older version of firebase_messaging that we had been using (5.1.8). That did not fix it.

What did fix it (but, feels wrong) was to add back android:name="io.flutter.app.FlutterApplication" (which the Flutter upgrade pre 1.12 instructions said to remove).

Given that I had removed the android.name attribute while following update instructions for the barcode_scan and image packages, I built a prod build, and tested barcode scanning, the camera, and notifications. With that attribute added back, the image, barcode_scan, and firebase_messaging plugins are all working (for me in Android).

It get that YYMV. And I would rather not do something against the upgrade instructions. But, this is how I'm going to leave it for now. Looking forward to hearing if there is a better long term solution.

Just for reference. Here is my Flutter Doctor.

Doctor summary (to see all details, run flutter doctor -v):
[βœ“] Flutter (Channel stable, v1.17.4, on Linux, locale en_US.UTF-8)
[βœ“] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[βœ“] Android Studio (version 3.6)
[βœ“] VS Code (version 1.46.1)
[βœ“] Connected device (1 available)

! Doctor found issues in 1 category.
niypoo commented 3 years ago

I have facing this issue the google crashlytics catch these issues

Screen Shot 2020-07-12 at 11 18 29 AM Screen Shot 2020-07-12 at 11 18 39 AM
philipgiuliani commented 3 years ago

@niypoo The bug that you posted is the following: https://github.com/flutter/flutter/issues/37566

This is the suggested fix: https://github.com/flutter/flutter/issues/37566#issuecomment-647800555

niypoo commented 3 years ago

@niypoo The bug that you posted is the following: flutter/flutter#37566

This is the suggested fix: flutter/flutter#37566 (comment)

thanks @philipgiuliani I will try that suggested fix

ThinkSimple commented 3 years ago

@niypoo The bug that you posted is the following: flutter/flutter#37566

This is the suggested fix: flutter/flutter#37566 (comment)

Does not work for me... It still crashes when the app is terminated and recieves a notification.

juzejunior commented 3 years ago

Hello guys, i'm having this issue too in a production environment, really need help, background notification is essential for my app, started after upgrading for android embedding v2, I have also updated to the latest version fo firebase_messaging package ^7.0.0.

Crashlytics:

Fatal Exception: java.lang.RuntimeException Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.RuntimeException: PluginRegistrantCallback is not set. android.app.ActivityThread.handleCreateService

EmbeddingV1Activity: `package br.com.spacerocket.constante import android.os.Bundle import io.flutter.app.FlutterActivity import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin

class EmbeddingV1Activity: FlutterActivity() { override protected fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) FirebaseMessagingPlugin.registerWith(registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")) } }`

Android Manifest:

`<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="br.com.spacerocket.constante">

<!-- 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:label="Constante"
    android:name="io.flutter.app.FlutterApplication"
    android:icon="@mipmap/ic_launcher"
    >
    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />
    <!-- Set custom default icon. This is used when no icon is set for incoming notification messages. -->
    <meta-data
     android:name="com.google.firebase.messaging.default_notification_icon"
     android:resource="@drawable/ic_notification" />

     <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming notification message.  -->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorAccent" />   

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

        <!-- Specify that the launch screen should continue being displayed -->
        <!-- until Flutter renders its first frame. -->
        <meta-data
            android:name="io.flutter.embedding.android.SplashScreenDrawable"
            android:resource="@drawable/launch_background" />

        <!-- Theme to apply as soon as Flutter begins rendering frames -->
        <meta-data
            android:name="io.flutter.embedding.android.NormalTheme"
            android:resource="@style/NormalTheme"
            />

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

    <!--keep compatibility -->
    <activity
        android:name=".EmbeddingV1Activity"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">
    </activity>

    <!-- Facebook Login configuration -->
    <meta-data android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id"/>

    <activity android:name="com.facebook.FacebookActivity"
        android:configChanges=
            "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name" 
        android:exported="true"
        />
    <activity
        android:name="com.facebook.CustomTabActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
    </activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.android.vending.BILLING" />

`

gabdsg commented 3 years ago

I have the same problem Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.IllegalStateException: ensureInitializationComplete must be called after startInitialization

OndrejPsencik commented 3 years ago

There are multiple issues with fcm plugin. IllegalStateException can be solved by following recipe:

create application class

Kotlin:

class WorkaroundApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        FlutterMain.startInitialization(this)
        FlutterFirebaseMessagingService.setPluginRegistrant {}
    }
}

set this class as application class in Android manifest

<application
            android:name=".WorkaroundApplication"
            android:label="@string/app.name"
            android:icon="@mipmap/ic_launcher"
            android:allowBackup="false"
    >

there is complicated issue when application process is stopped and notification comes. Background notifications processing (in flutter) does not work and will not probably soon or ever work when application process is stopped. With this workaround there will be at least shown tray notification and background notification will crash in flutter code, not Android so Android process will not be crashed (which has further unpleasant consequences).

jorgeroncero commented 3 years ago

The firebase_messaging plugin is not ready for Android v2 embedding. For that, they should:

  1. Remove the references to FlutterMain.ensureInitializationComplete which is called twice in the java code.
  2. Change FlutterNativeView related code to FlutterEngine related code.
  3. Change pluginRegistrantCallback mandatory requirement to optional (since it will only be used in v1 embedding)

For now, you must use v1 embedding as described in their README or modify the FlutterFirebaseMessagingService.java file on your local plugins folder with the above instructions.

jorgeroncero commented 3 years ago

I have created a PR#3572 that should fix this issue if you are using v2 embedding (i.e. you removed the .Application reference in your manifest). Let me know if this is working for you

juzejunior commented 3 years ago

@jronceroscb hello, i tested here and i'm getting this error when sending notification:

java.lang.RuntimeException: Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.NullPointerException: Attempt to read from field 'java.lang.String io.flutter.view.FlutterCallbackInformation.callbackLibraryPath' on a null object reference E/AndroidRuntime(25801): at android.app.ActivityThread.handleCreateService(ActivityThread.java:3544) E/AndroidRuntime(25801): at android.app.ActivityThread.access$1300(ActivityThread.java:199) E/AndroidRuntime(25801): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1666) E/AndroidRuntime(25801): at android.os.Handler.dispatchMessage(Handler.java:106) E/AndroidRuntime(25801): at android.os.Looper.loop(Looper.java:193) E/AndroidRuntime(25801): at android.app.ActivityThread.main(ActivityThread.java:6669) E/AndroidRuntime(25801): at java.lang.reflect.Method.invoke(Native Method) E/AndroidRuntime(25801): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) E/AndroidRuntime(25801): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) E/AndroidRuntime(25801): Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String io.flutter.view.FlutterCallbackInformation.callbackLibraryPath' on a null object reference E/AndroidRuntime(25801): at io.flutter.embedding.engine.dart.DartExecutor$DartCallback.toString(DartExecutor.java:325) E/AndroidRuntime(25801): at java.lang.String.valueOf(String.java:2896) E/AndroidRuntime(25801): at java.lang.StringBuilder.append(StringBuilder.java:132) E/AndroidRuntime(25801): at io.flutter.embedding.engine.dart.DartExecutor.executeDartCallback(DartExecutor.java:141) E/AndroidRuntime(25801): at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:170) E/AndroidRuntime(25801): at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.onCreate(FlutterFirebaseMessagingService.java:85) E/AndroidRuntime(25801): at android.app.ActivityThread.handleCreateService(ActivityThread.java:3532)

jorgeroncero commented 3 years ago

Hi @juzejunior , can you elaborate? What is your flutter version? How are you setting up Firebase Messaging? What is your Android MainActivity/Application and your manifest?

From your log, I see executions at lines that are not right for the FlutterFirebaseMessagingService.java file (85 is not onCreate and 170 shouldnt crash at all)

ViniciusSossela commented 3 years ago

While it is not fixed, the following workaround solved the issue for me:

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.FlutterInjector;
import androidx.annotation.CallSuper;

public class MainActivity extends FlutterActivity {

    @Override
    @CallSuper
    protected void onStart() {
        super.onStart();
        FlutterInjector.instance().flutterLoader().startInitialization(this);
    }
}
steffenhaak commented 3 years ago

Hi @jronceroscb, first of all, thank you for your effort!

I just tried to use your PR by directly referencing your fork in pubspec.yml. I get the same error as juzejunior, but with correct line numbers, see below. Maybe this helps.

I do have a customized FlutterActivity, as I am offering a "share" functionality in my app.

Flutter (Channel stable, 1.20.4, on Mac OS X 10.15.6 19G2021, locale de-DE)

W/FlutterEngine(29300): Tried to automatically register plugins with FlutterEngine (io.flutter.embedding.engine.FlutterEngine@1f6857e) but could not find and invoke the GeneratedPluginRegistrant.
D/AndroidRuntime(29300): Shutting down VM
E/AndroidRuntime(29300): FATAL EXCEPTION: main
E/AndroidRuntime(29300): Process: com.klubraum.androidApp.dev, PID: 29300
E/AndroidRuntime(29300): java.lang.RuntimeException: Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.NullPointerException: Attempt to read from field 'java.lang.String io.flutter.view.FlutterCallbackInformation.callbackLibraryPath' on a null object reference
E/AndroidRuntime(29300):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:4412)
E/AndroidRuntime(29300):    at android.app.ActivityThread.access$1800(ActivityThread.java:274)
E/AndroidRuntime(29300):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2118)
E/AndroidRuntime(29300):    at android.os.Handler.dispatchMessage(Handler.java:107)
E/AndroidRuntime(29300):    at android.os.Looper.loop(Looper.java:237)
E/AndroidRuntime(29300):    at android.app.ActivityThread.main(ActivityThread.java:8154)
E/AndroidRuntime(29300):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(29300):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
E/AndroidRuntime(29300):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
E/AndroidRuntime(29300): Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String io.flutter.view.FlutterCallbackInformation.callbackLibraryPath' on a null object reference
E/AndroidRuntime(29300):    at io.flutter.embedding.engine.dart.DartExecutor$DartCallback.toString(DartExecutor.java:325)
E/AndroidRuntime(29300):    at java.lang.String.valueOf(String.java:2924)
E/AndroidRuntime(29300):    at java.lang.StringBuilder.append(StringBuilder.java:132)
E/AndroidRuntime(29300):    at io.flutter.embedding.engine.dart.DartExecutor.executeDartCallback(DartExecutor.java:141)
E/AndroidRuntime(29300):    at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:165)
E/AndroidRuntime(29300):    at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.onCreate(FlutterFirebaseMessagingService.java:80)
E/AndroidRuntime(29300):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:4400)
E/AndroidRuntime(29300):    ... 8 more
jorgeroncero commented 3 years ago

Hi @jronceroscb, first of all, thank you for your effort!

I just tried to use your PR by directly referencing your fork in pubspec.yml. I get the same error as juzejunior, but with correct line numbers, see below. Maybe this helps.

I do have a customized FlutterActivity, as I am offering a "share" functionality in my app.

Flutter (Channel stable, 1.20.4, on Mac OS X 10.15.6 19G2021, locale de-DE)

W/FlutterEngine(29300): Tried to automatically register plugins with FlutterEngine (io.flutter.embedding.engine.FlutterEngine@1f6857e) but could not find and invoke the GeneratedPluginRegistrant.
D/AndroidRuntime(29300): Shutting down VM
E/AndroidRuntime(29300): FATAL EXCEPTION: main
E/AndroidRuntime(29300): Process: com.klubraum.androidApp.dev, PID: 29300
E/AndroidRuntime(29300): java.lang.RuntimeException: Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.NullPointerException: Attempt to read from field 'java.lang.String io.flutter.view.FlutterCallbackInformation.callbackLibraryPath' on a null object reference
E/AndroidRuntime(29300):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:4412)
E/AndroidRuntime(29300):  at android.app.ActivityThread.access$1800(ActivityThread.java:274)
E/AndroidRuntime(29300):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2118)
E/AndroidRuntime(29300):  at android.os.Handler.dispatchMessage(Handler.java:107)
E/AndroidRuntime(29300):  at android.os.Looper.loop(Looper.java:237)
E/AndroidRuntime(29300):  at android.app.ActivityThread.main(ActivityThread.java:8154)
E/AndroidRuntime(29300):  at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(29300):  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
E/AndroidRuntime(29300):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
E/AndroidRuntime(29300): Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String io.flutter.view.FlutterCallbackInformation.callbackLibraryPath' on a null object reference
E/AndroidRuntime(29300):  at io.flutter.embedding.engine.dart.DartExecutor$DartCallback.toString(DartExecutor.java:325)
E/AndroidRuntime(29300):  at java.lang.String.valueOf(String.java:2924)
E/AndroidRuntime(29300):  at java.lang.StringBuilder.append(StringBuilder.java:132)
E/AndroidRuntime(29300):  at io.flutter.embedding.engine.dart.DartExecutor.executeDartCallback(DartExecutor.java:141)
E/AndroidRuntime(29300):  at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:165)
E/AndroidRuntime(29300):  at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.onCreate(FlutterFirebaseMessagingService.java:80)
E/AndroidRuntime(29300):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:4400)
E/AndroidRuntime(29300):  ... 8 more

The "Tried to automatically register plugins with FlutterEngine (io.flutter.embedding.engine.FlutterEngine@1f6857e) but could not find and invoke the GeneratedPluginRegistrant." line suggests me that you are not using the v2 embedding in your manifest, i.e. you don't have

<meta-data android:name="flutterEmbedding" android:value="2" />

inside your application node. Can you confirm this?

Anyways, the plugin should also work with v1 embedding, so, can you share some of that Flutter Activity (Main Activity) code to reproduce on my end?

And thanks for taking the effort to test my fork!

steffenhaak commented 3 years ago

Can you confirm this?

Unfortunately I cannot confirm this. I had switched to v2 embedding completely, exactly according to the guide, and meanwhile rely on the workaround described by MooNag. Maybe it is because I have a custom FlutterActivity?

If I can help you with any further information, let me know.

Regards, Steffen

jorgeroncero commented 3 years ago

Can you confirm this?

Unfortunately I cannot confirm this. I had switched to v2 embedding completely, exactly according to the guide, and meanwhile rely on the workaround described by MooNag. Maybe it is because I have a custom FlutterActivity?

If I can help you with any further information, let me know.

Regards, Steffen

Thanks again Steffen for answering. Let's see if we can manage to reproduce your environment on my end to fix this. If you can provide me some code of your:

Thanks in advance

steffenhaak commented 3 years ago

Sounds like a good plan :) Thanks once again for trying to solve this puzzle!

AndroidManifest.xml

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

    <!-- The INTERNET permission is required for development. Specifically,
         flutter needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>

    <!-- permissions needed for multi_image_picker -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:label="${applicationLabel}"
        android:icon="@mipmap/ic_launcher"
        android:allowBackup="false"
        android:fullBackupContent="false">
        <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 ui.components.splash screen (such as the default ui.components.splash screen
                 defined in @style/LaunchTheme). -->
            <meta-data
                android:name="io.flutter.embedding.android.SplashScreenDrawable"
                android:resource="@drawable/launch_background" />

            <!-- Theme to apply as soon as Flutter begins rendering frames -->
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme"
                />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

            <!-- Firebase Messaging -->
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <!-- App Links (Login-Link, Conversations) -->
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data
                    android:scheme="https"
                    android:host="${appLinkHost}" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="text/plain"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="image/png"/>
                <data android:mimeType="image/jpeg"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND_MULTIPLE"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="image/png"/>
                <data android:mimeType="image/jpeg"/>
            </intent-filter>
        </activity>
        <activity
            android:name="com.yalantis.ucrop.UCropActivity"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        </activity>
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
        <meta-data android:name="com.google.android.geo.API_KEY"
            android:value="**************"/>
</application>
</manifest>

MainActivity.class

package com.example.app;

import androidx.annotation.NonNull;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
import com.example.app.plugins.share.FlutterShareReceiverActivity;

import android.util.Log;

public class MainActivity extends FlutterShareReceiverActivity {

  @Override
  protected void registerPlugins(@NonNull FlutterEngine flutterEngine) {
    Log.i(getClass().getSimpleName(), "initializing plugins");
    GeneratedPluginRegistrant.registerWith(flutterEngine);
  }
}

FlutterShareReceiverActivity is located in a separate plugin and contains the following code:

public abstract class FlutterShareReceiverActivity extends FlutterActivity {

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        registerPlugins(flutterEngine);
        if (!inited) {
            init(flutterEngine, this);
        }
        handleIntent(getIntent());
    }

    protected abstract void registerPlugins(@NonNull FlutterEngine flutterEngine);

    public void init(@NonNull FlutterEngine flutterEngine, Context context) {
        Log.i(getClass().getSimpleName(), "initializing share eventChannel");
        //omitted

     }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    public void handleIntent(Intent intent) {
       //omitted
    }
}

I tried to remove all unrelated code above. Hope this still provides enough information.

Cheers, Steffen

jorgeroncero commented 3 years ago

@steffenhaak I've tested with your exact custom activity setup and it's working perfectly fine.

Is that share plugin publicly available? I've checked flutter-share and ShareImage-Flutter repos but they don't have exactly the same code that you've posted.

Thanks again