简体   繁体   English

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

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

My problem is that I don't receive the firebase cloud message in my android app client, which I send from my Spring MVC app.我的问题是我在我的 android 应用程序客户端中没有收到 firebase 云消息,这是我从 Spring MVC 应用程序发送的。 Here is the code in the Spring App Test.这是 Spring App Test 中的代码。

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

My pom.xml:我的 pom.xml:

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

When I ran the Unit test in the Spring MVC Project I am getting the result:当我在 Spring MVC 项目中运行单元测试时,我得到了结果:

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

And here is my android app client code: AndroidManifest.xml这是我的 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 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 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());
        }

    }
}

Added the google-services.json in the app folder.在 app 文件夹中添加了 google-services.json。 build.gradle:构建.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:应用程序/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'
}

In the logcat of the android app I never received any Message from the firebase!在 android 应用程序的 logcat 中,我从未收到来自 firebase 的任何消息! I don't know what I am missing here.我不知道我在这里错过了什么。

UPDATE 1: The app is in the foreground and running, and I don't receiving nothing from the firebase.更新 1:该应用程序处于前台并正在运行,我没有收到任何来自 firebase 的信息。

You have to show a Notification once the message is received.收到消息后,您必须显示通知。 So, call this below function in onMessageReceived() in MyFirebaseInstanceIDService.java .因此,在MyFirebaseInstanceIDService.javaonMessageReceived()中调用以下函数。 But first, make sure you are getting a response from the server.但首先,请确保您从服务器获得响应。

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 控制台重新检查配置文件,清理构建和重建并最终工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我无法在我的 android 仿真器中接收 Firebase 云消息传递 FCM - I Can' t receive the Firebase Cloud Messaging FCM In my android emulator 套接字服务器,我没有收到服务器发送的消息 - Socket server, I don't receive the message sent by my Server 我的应用程序未收到解析通知 - my app don't receive a parse notifications Android改装我没有收到JSON - Android Retrofit I don't receive JSON 我在智能手机上收到的数据包不多 - i don't receive more then one packet on my smartphone 我没有收到对我的 BroadcastReceiver 的操作 - AndroidStudio - I don't receive an action on my BroadcastReceiver - AndroidStudio Firebase:在我说之前,不要向所有听众发送消息 - Firebase: Don't send message to all the listeners until I say Google Cloud Messaging:iOS App处于后台时不会收到提醒 - Google Cloud Messaging: don't receive alerts when iOS App is in background 当我的 android App 收到 firebase 消息通知,然后关机 - When my android App get firebase message notification, then shutting down 我没有收到我为了第二个活动而传递的字符串 - I don't receive the String I passed with an intent on my second activity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM