.getToken() 调用时 Flutter firebase_messaging android 应用程序崩溃

Flutter firebase_messaging android app crash on .getToken() call

我正在尝试将 firebase_messaging 包与我的 flutter 应用集成。通常它可以正常工作(7.0.3 版)我正在使用的代码(见下文)但是自从空安全版本发布后我的代码就不再工作了。我想知道是否有人可以帮助我找出我做错了什么?

导致代码错误

try {
    fcmToken = await _firebaseMessaging.getToken();
} catch (error) {
    print(error);
}

错误输出

E/AndroidRuntime( 8942): java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/iid/Metadata;
E/AndroidRuntime( 8942):    at io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin.lambda$getToken$FlutterFirebaseMessagingPlugin(FlutterFirebaseMessagingPlugin.java:165)
E/AndroidRuntime( 8942):    at io.flutter.plugins.firebase.messaging.-$$Lambda$FlutterFirebaseMessagingPlugin$p8YQXDuFBNIxl8PFaPCQJtYc3sw.call(Unknown Source:4)
E/AndroidRuntime( 8942):    at com.google.android.gms.tasks.zzv.run(Unknown Source:2)
E/AndroidRuntime( 8942):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/AndroidRuntime( 8942):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/AndroidRuntime( 8942):    at java.lang.Thread.run(Thread.java:923)
E/AndroidRuntime( 8942): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.iid.Metadata" on path: DexPathList[[zip file "/data/app/~~uCa7QFzhvu5i_TZpnqat0w==/com.example.****-1cbY-LKuCoOsfZybV-Gq6g==/base.apk"],nativeLibraryDirectories=[/data/app/~~uCa7QFzhvu5i_TZpnqat0w==/com.example.****-1cbY-LKuCoOsfZybV-Gq6g==/lib/x86, /data/app/~~uCa7QFzhvu5i_TZpnqat0w==/com.example.****-1cbY-LKuCoOsfZybV-Gq6g==/base.apk!/lib/x86, /system/lib, /system_ext/lib]]
E/AndroidRuntime( 8942):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:207)
E/AndroidRuntime( 8942):    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
E/AndroidRuntime( 8942):    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/AndroidRuntime( 8942):    ... 6 more

app -> src -> main -> kotlin -> Application.kt

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry

import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin

class Application() : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun registerWith(registry: PluginRegistry?) {
        val key: String? = FlutterFirebaseMessagingPlugin::class.java.canonicalName
        if (!registry?.hasPlugin(key)!!) {
            FlutterFirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin"));
        }
    }
}

app -> src -> main -> kotlin -> MainActivity.kt

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}

解决方案

出于某种原因,我将 onBackgroundMessageHandler 作为 class 方法放入我的项目中。只需将该方法按原样放置为 顶级函数 即可解决问题。

之前

class MyNotificationClass {
      Future<dynamic> onBackgroundMessageHandler(RemoteMessage message) async {
        print('on Background $message');
      }

      // ...
    }

之后

Future<dynamic> onBackgroundMessageHandler(RemoteMessage message) async {
            print('on Background $message');
          }

class MyNotificationClass {
          // ...
        }

android -> 应用程序 -> src -> build.gradle

dependencies {
    implementation 'com.google.android.material:material:1.3.0'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Import the Firebase BoM
    implementation platform('com.google.firebase:firebase-bom:26.3.0')

    // Add the dependency for the Firebase SDK for Google Analytics
    // When using the BoM, don't specify versions in Firebase dependencies
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-auth'
    implementation 'com.google.firebase:firebase-messaging'
}
// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

android -> build.gradle

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        //classpath 'com.android.tools.build:gradle:4.1.0'
        classpath 'com.android.tools.build:gradle:3.5.3' // 3.5.0
        classpath 'com.google.gms:google-services:4.3.2' // 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}"
    project.evaluationDependsOn(':app')
}

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

pubspec.yaml

  cloud_firestore: ^1.0.5 #^0.14.4 #^0.13.5                     
  firebase_database: ^6.1.2 #4.4.0                             
  firebase_core: ^1.0.3 #^0.5.3 #^0.4.4+3                       
  firebase_auth: ^1.1.0 #0.18.4+1 #^0.16.0                     
  firebase_messaging: ^9.1.1 #7.0.3 #^6.0.15                   
  firebase_dynamic_links: ^2.0.0 #0.6.3 #^0.5.0+11             
  firebase_analytics: ^8.0.0 #6.3.0 #^5.0.11                   
  cloud_functions: ^1.0.3 #0.7.2 #^0.5.0                       

AndroidManifest.xml

<application
        android:name=".Application"
        android:label="app name"
        android:usesCleartextTraffic="true"
        android:icon="@mipmap/ic_launcher">

        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme"
                />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
                android:name="io.flutter.embedding.android.SplashScreenDrawable"
                android:resource="@drawable/launch_background"
                />
            <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>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_notification" />

        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>

对我来说,它通过从

降级来工作

com.google.firebase:firebase-bom:28.0.1

com.google.firebase:firebase-bom:27.0.0

提示:这是针对以下版本的临时解决方案:

firebase_messaging: ^9.1.4 firebase_core: ^1.1.1