我的 android 应用中没有收到 Firebase 云消息

I don't receive the Firebase Cloud Message in my android app

我的问题是我的 android 应用程序客户端没有收到 firebase 云消息,这是我从 Spring MVC 应用程序发送的。 这是 Spring 应用测试中的代码。

 GoogleCredentials googleCredentials = GoogleCredentials
                    .fromStream(new ClassPathResource("my-config.json").getInputStream());
            FirebaseOptions firebaseOptions = FirebaseOptions
                    .builder()
                    .setCredentials(googleCredentials)
                    .build();
            FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "my-app");
            FirebaseMessaging firebaseMessaging = FirebaseMessaging.getInstance(app);
            Notification notification = Notification
                    .builder()
                    .setTitle("My title")
                    .setBody("My body")
                    .build();

            Message message = Message
                    .builder()
                    .setTopic("test1")
                    .build();

            String result = firebaseMessaging.send(message);
            System.out.println("result:" + result);

我的pom.xml:

<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>7.3.0</version>
</dependency>

当我 运行 在 Spring MVC 项目中进行单元测试时,我得到的结果是:

result:projects/heliosemenu-9eba9/messages/6047526430479807699

这是我的 android 应用客户端代码: AndroidManifest.xml

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

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FirebaseApp.initializeApp(getApplicationContext());

        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(@NonNull Task<String> task) {
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
                            return;
                        }

                        // Get new FCM registration token
                        String token = task.getResult();

                        // Log and toast
                        String msg = getString(R.string.msg_token_fmt, token);
                        Log.d(TAG, msg);
                        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });



        FirebaseMessaging.getInstance().setAutoInitEnabled(true);

        FirebaseMessaging.getInstance().subscribeToTopic("HeliosEMenuTest").
                addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
                            return;
                        }

                        // Get new FCM registration token

                        Log.i(TAG,task.isSuccessful()+"|");
                    }
                });
    }

MyFirebaseInstanceIDService.java

public class MyFirebaseInstanceIDService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseInstanceIDService";

    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);

    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        }

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

    }
}

在应用程序文件夹中添加了 google-services.json。 build.gradle:

buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.3.10'
    }
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.3' apply false
    id 'com.android.library' version '7.1.3' apply false
}

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

app/build.gradle:

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

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.heliosfirebasereceiver"
        minSdk 26
        targetSdk 32
        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.4.1'
    implementation 'com.google.android.material:material:1.6.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.google.firebase:firebase-messaging:23.0.5'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

在 android 应用程序的 logcat 中,我从未收到来自 firebase 的任何消息!我不知道我在这里错过了什么。

更新 1: 该应用程序在前台 运行,我没有收到来自 firebase 的任何信息。

您必须在收到消息后显示通知。因此,在 MyFirebaseInstanceIDService.java 中的 onMessageReceived() 中调用下面的函数。但首先,请确保您正在从服务器获得响应。

private void showNotification(@NonNull RemoteMessage remoteMessage) {
    
            String channelId = "fcm_default_channel";
            NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(this, channelId)
                            .setSmallIcon(R.drawable.ic_notification)
                            .setContentTitle(title)
                            .setContentText(remoteMessage.getNotification().getBody();
    
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
            // Since android Oreo notification channel is needed.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(channelId,
                        "Channel human readable title",
                        NotificationManager.IMPORTANCE_DEFAULT);
                notificationManager.createNotificationChannel(channel);
            }
    
            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
}

我从 firebase 控制台重新检查了配置文件,清理构建并重新构建,终于成功了。