Android Studio logcat 中未显示 Firebase 注册令牌

Firebase registration token is not showing in Android Studio logcat

我使用的是 Android studio Arctic Fox 版本。我需要实现一个自动通知应用程序,它将按日期发送通知。我 运行 我的应用程序在 6.0.1 android 版本的实际设备上。我已经连接了 fcm 并设置了依赖项。但是 logcat 上没有显示令牌。还在 firebase 中注册了该应用程序。知道为什么会这样吗?

构建:gradle(:app)

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.f1"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    implementation 'com.google.firebase:firebase-messaging:22.0.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

构建:gradle(模块)

  dependencies {
        classpath "com.android.tools.build:gradle:7.0.2"
        classpath 'com.google.gms:google-services:4.3.10'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}


manifest.xml

<service android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(@NonNull String s)
    {
        super.onNewToken(s);
        Log.d("My token", "Refreshed Token"+s);
        sendRegistrationToServer(s);
    }

    private void sendRegistrationToServer(String s) {
    }
    
}

如果您在添加 MyFirebaseMessagingService 代码之前 运行 设备上的应用程序,那么它可能已经生成了一个令牌。添加 MyFirebaseMessagingService 不会生成新令牌,因此不会调用您的 onNewToken

在这种情况下获取令牌的两个选项是:

  1. 从(例如)主 activity 调用 FirebaseMessaging.getInstance().getToken() 并在那里调用相同的 sendRegistrationToServer
  2. 添加 FirebaseMessaging.getInstance().getToken() 代码后删除应用及其数据,然后重新安装应用。删除数据会删除令牌,因此当您 运行 应用程序时,它将生成一个新令牌并调用您的 onNewToken.