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

阿琼拉姆

我正在尝试构建一个可以在数据库中更改某个值时接收通知的应用程序。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);
        }
    }

MyFirebase 消息服务:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我的寻找圆线碰撞解决方案的函数可能有什么问题?

我的依赖项或权限可能有什么问题?

这种 uml 关系可能有什么问题

在此php代码中可能有什么问题?

我没有从控制台的Firebase收到消息消息

在使用 adodb 存储的 mysql 列中查找 Sum 的 PHP 代码中可能有什么问题?

我的iPhone上没有收到推送通知,但是Firebase Functions说它成功交付了吗?

代码只是没有执行,可能有语法问题,或者我可能是完全错误的

我的功能有什么问题?

这个 Redux (react) 应用程序可能有什么问题?

这个 SQL 语法 Sqlite3 可能有什么问题?

该批处理文件中可能有什么问题

我从Firebase检索电子邮件信息的代码有什么问题?

我的$ firebase $ loaded服务中的诺言有什么问题?

为什么我的换行符无法正常工作?flex可能有问题吗?

没有输出,我的代码有什么问题?

请使用Java中的此自动化Mysql DB connecton可能有什么问题

Javascript 音频在前 3 次点击后无法播放,从第 4 次点击开始播放,没有任何问题,可能有什么问题?

为什么我没有收到插槽?

我的比较功能有什么问题?

我的反转循环链表的功能有什么问题。?

我的存储库功能有什么问题?

我的主要功能有什么问题

我的 vigenere 密码加密功能有什么问题?

此功能有什么问题?它使我的程序崩溃而没有错误

我的Angular代码有什么问题?

我的lua代码有什么问题?

我的Listview代码有什么问题?

我的 LRUCache 代码有什么问题