【问题标题】:Error while sending notifications to multiple users using Firebase Functions使用 Firebase 函数向多个用户发送通知时出错
【发布时间】:2017-12-13 21:56:35
【问题描述】:

我正在开发一个安卓博客应用,当管理员发布博客时,通知必须发送给所有使用该应用的用户。

问题是管理员发布博客时没有发送通知。 我正在使用 nodejs,这里是代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.pushNotification = functions.database.ref('/notifications/{pushId}').onWrite( event => {

    console.log('Push notification event triggered');


    var valueObject = event.data.val();
        const titleIs = event.params.pushId;

        console.log('Title is: ', titleIs);

    const payload = {
        notification: {
                title : "New status Update",
                body: "There is a new status for you!",
                icon: "default"            
        },
    };

    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24
    };

    return admin.messaging().sendToTopic("pushNotifications", payload, options)
        .then(function(response) {
            console.log("Successfully sent notification: ", response.message);
        })
        .catch(function(error) {
            console.log("Error sending notification: ", error)
        });
});

这是服务的 java 文件:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FirebaseMessagingServce";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String notificationTitle = null, notificationBody = null;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            notificationTitle = remoteMessage.getNotification().getTitle();
            notificationBody = remoteMessage.getNotification().getBody();
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
        sendNotification(notificationTitle, notificationBody);
    }


    private void sendNotification(String notificationTitle, String notificationBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setAutoCancel(true)   //Automatically delete the notification
                .setSmallIcon(R.mipmap.ic_launcher) //Notification icon
                .setContentIntent(pendingIntent)
                .setContentTitle(notificationTitle)
                .setContentText(notificationBody)
                .setSound(defaultSoundUri);


        NotificationManager notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }
}

这是管理员发布博客时的代码

private void startPosting() {

        mProgressDialog.setMessage("Posting to Status ...");

        final String title_value = mStatusTitleEditText.getText().toString().trim();
        final String description_value = mStatusDescriptionEditText.getText().toString().trim();

        if (!TextUtils.isEmpty(title_value) && !TextUtils.isEmpty(description_value)
                && mImageUri != null) {

            mProgressDialog.show();

            StorageReference mFilePath =
                    mStorage.child("Status_Images").child(mImageUri.getLastPathSegment());

            mFilePath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask
                    .TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    //DB
                    HashMap<String, String> notificationData = new HashMap<>();
                    notificationData.put("from", "admin");

                    mNotificationDatabase.push().setValue(notificationData)
                            .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Toast.makeText(PostActivity.this, "Added to database",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });

                    @SuppressWarnings("VisibleForTests")
                    Uri downloadUrl = taskSnapshot.getDownloadUrl();

                    DatabaseReference newPost = mDatabase.push();
                    newPost.child("title").setValue(title_value);
                    newPost.child("description").setValue(description_value);

                    newPost.child("date").setValue(System.currentTimeMillis());

                    newPost.child("image").setValue(downloadUrl.toString());


                    mProgressDialog.dismiss();

                    FirebaseMessaging.getInstance().subscribeToTopic("pushnotifications");

                    startActivity(new Intent(PostActivity.this, MainActivity.class));
                }
            });
        }
    }

【问题讨论】:

  • 你确定你的函数有问题吗?您在客户端实现消息传递也可能存在问题。
  • 谢谢!我检查了日志,该功能没有问题。我已经编辑了我的问题。
  • 您没有使用您定义的选项。将它们作为调用中的第三个参数传递给sendToTopic()sendToTopic("pushNotifications", payload, options)。这可能不是主要问题,但包含高优先级将确保在设备处于睡眠状态时传递消息。
  • 从 Firebase 控制台发送到主题 pushNotifications 时,您的应用是否收到通知?
  • 应用没有收到任何通知。这是我从函数日志中得到的:成功发送通知:{ messageId: 5259382823931248000 }

标签: android node.js firebase firebase-cloud-messaging google-cloud-functions


【解决方案1】:

您在使用主题名称时存在拼写错误。在云功能中,您将发布到pushNotifications。在您的应用中,您订阅主题 pushnotifications(全部小写)。

【讨论】:

  • 我已经修正了错字但仍然没有成功。
  • 检查你的 logcat 是否有警告提示 W/GooglePlayServicesUtil: Google Play services out of date
猜你喜欢
  • 2020-11-30
  • 2021-10-07
  • 2020-05-31
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
相关资源
最近更新 更多