使用Firebase功能向多个用户发送通知时出错

时间:2017-12-13 21:56:35

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

我正在开发一个Android博客应用程序,当管理员发布博客时,必须使用该应用程序向所有用户发送通知。

问题是管理员发布博客时没有发送通知。 我正在使用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));
                }
            });
        }
    }

1 个答案:

答案 0 :(得分:0)

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