我没有收到 Firebase 通知。我的代码可能有什么问题?

I'm not receiving Firebase Notifications. What could be wrong with my code?

我正在尝试构建一个可以在数据库中更改特定值时接收通知的应用程序。 Cloud Functions 的代码部分正在正确执行,但我的应用程序未收到通知。可能是什么问题呢?我附上了下面的代码,请帮帮我!

MyFirebaseInstanceIdService:

   public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
        private static final String TAG = "MyFirebaseIIDService";

        /**
         * Called if InstanceID token is updated. This may occur if the security of
         * the previous token had been compromised. Note that this is called when the InstanceID token
         * is initially generated so this is where you would retrieve the token.
         */
        @Override
        public void onTokenRefresh() {
            // Get updated InstanceID token.
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            sendRegistrationToServer(refreshedToken);
        }


        /**
         * Persist token to third-party servers.
         *
         * Modify this method to associate the user's FCM InstanceID token with any server-side account
         * maintained by your application.
         *
         * @param token The new token.
         */
        private void sendRegistrationToServer(String token) {
            DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
            reference
                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                    .setValue(token);
        }
    }

MyFirebaseMessagingService:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";
    private static final int BROADCAST_NOTIFICATION_ID = 1;

    @Override
    public void onDeletedMessages() {
        super.onDeletedMessages();
    }

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String notificationBody = "";
        String notificationTitle = "";
        String notificationData = "";
        try{
            notificationData = remoteMessage.getData().toString();
            notificationTitle = remoteMessage.getNotification().getTitle();
            notificationBody = remoteMessage.getNotification().getBody();
        }catch (NullPointerException e){

        }


        String dataType = remoteMessage.getData().get("direct_message");
        if(dataType.equals("direct_message")){
            String title = remoteMessage.getData().get("title");
            String message = remoteMessage.getData().get("message");
            sendMessageNotification(title, message);
        }
    }

    /**
     * Build a push notification for a chat message
     * @param title
     * @param message
     */
    private void sendMessageNotification(String title, String message){
        //get the notification id


        int notificationId = (int) System.currentTimeMillis();

        // Instantiate a Builder object.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default");
        // Creates an Intent for the Activity
        Intent pendingIntent = new Intent(this, ChatActivity.class);
        // Sets the Activity to start in a new, empty task
        pendingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        // Creates the PendingIntent
        PendingIntent notifyPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        pendingIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

        //add properties to the builder
        builder.setSmallIcon(R.drawable.ic_notif)
                .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(),
                        R.drawable.ic_notif))
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setContentTitle(title)
                .setAutoCancel(true)
                //.setSubText(message)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                .setOnlyAlertOnce(true);

        builder.setContentIntent(notifyPendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        mNotificationManager.notify(notificationId, builder.build());

    }




}

我的 Firebase 函数代码:

exports.rentPaid = functions.database.ref('/Rent_Paid_Status/{UserID}/status').onWrite((change, context) => {

  const current_status = change.after.val();

  const User_ID = context.params.UserID;

//  if(current_status.toString().trim() === "yes")
  //{

      const token_ref = admin.database().ref('/Tokens/User_ID');
      token_ref.once("value", function(data){

        //construct single value event listener.
            const token = data.val();
            console.log("token: ", token);

            //we have everythin g we need
            //Build the message payload and send the message
            console.log("Construction the notification message.");
            const payload = {
              data: {
                data_type: "direct_message",
                title: "Rent Paid",
                message: "Thank you for paying your rent!",
              }
            };

            return admin.messaging().sendToDevice(token, payload)
                  .then(function(response) {
                    console.log("Successfully sent message:", response);
                    })
                    .catch(function(error) {
                    console.log("Error sending message:", error);
                    });
            //send notif saying 'thank you for paying your rent!'


      });
  }

return null;

})

我的清单文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="vision.google.com.gudutenantapp">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Login.MainActivity">
        </activity>

        <service
            android:name=".Chat.MyFirebaseInstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

        <service
            android:name=".Chat.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>


        <activity android:name=".Chat.ChatActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>
        <activity android:name=".TenantSettingsActivity" />
        <activity android:name=".Login.Information_Activity" />
        <activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
            android:theme="@style/Base.Theme.AppCompat"/>
    </application>

收到消息dataType时,属性键错误:

改变这个:

String dataType = remoteMessage.getData().get("direct_message");

应该是:

String dataType = remoteMessage.getData().get("data_type");