Не удается получить уведомление на моем устройстве Android при отправке уведомления fcm через облачную функцию Firebase на триггеры базы данных - PullRequest
0 голосов
/ 26 января 2019

Я столкнулся с проблемой в облачном сообщении firebase, которое отправляется через облачную функцию firebase, которая запускается при событии onCreate в корневом каталоге / Users / {userid} моей базы данных реального времени. Облачная функция успешно выполняется согласно моим журналам.на firebase, но все равно я не получаю уведомление на моем устройстве Android, однако уведомление получено, когда я пытаюсь отправить его вручную через консоль firebase, но не в базе данных запускает

Вот моя облачная функция

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.sendNotification = functions.database.ref('/Users/{userId}').onCreate((snapshot,context)=> {
const data = snapshot.val()
const token = data.tokenId
console.log('The fcm token is '+token);
const name = data.name
const usrid = data.email
console.log('The user name is '+name);
console.log('new user with user Id '+usrid+' is Added')
const payload = {
    notification:{
        title: 'Hello '+name,
        body :'Welcome to Stydy Solutions'
    }
};
return admin.messaging().sendToDevice(token, payload)
                    .then(function(response) {
                        console.log("Successfully sent message:", response);
                      })
                      .catch(function(error) {
                        console.log("Error sending message:", error);
                      });
    });

Вот консольный журнал моей функции Cloud

Вот класс службы сообщений Firebase

 package com.saquib.hello.coachingapp;

 public class FirebaseMessagingServices extends FirebaseMessagingService{
@Override
public void onNewToken(String token) {
    super.onNewToken(token);
    FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            String refereshedtoken = instanceIdResult.getToken();
            Log.d("Hello", "initFCM: token: " + refereshedtoken);
            sendRegistrationToServer(refereshedtoken);
        }
    });
}

private void sendRegistrationToServer(String token) {
    Log.d("Hello", "sendRegistrationToServer: sending token to server: " + token);
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
    reference.child("Users")
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
            .child("messaging_token")
            .setValue(token);
}

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

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    String notificationBody = "";
    String notificationTitle = "";
    if (remoteMessage.getNotification() != null) {
        notificationBody = remoteMessage.getNotification().getBody();
        notificationTitle = remoteMessage.getNotification().getTitle();
        displayNotification(getApplicationContext(), notificationTitle, notificationBody);
    }
}

public static void displayNotification(Context context, String title, String body) {

        Intent intent = new Intent(context, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(
                context,
                100,
                intent,
                PendingIntent.FLAG_CANCEL_CURRENT
        );

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context, "Study Solutions")
                        .setSmallIcon(R.drawable.appicon)
                        .setContentTitle(title)
                        .setContentText(body)
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .setPriority(NotificationCompat.PRIORITY_HIGH);

        NotificationManagerCompat mNotificationMgr = NotificationManagerCompat.from(context);
        mNotificationMgr.notify(1, mBuilder.build());

    }

}

Это будет действительнополезно для меня, так как я потратил много времени на это, поиск в Google, просмотр лекций на YouTube и т. д., но ни один из них не помог мне!заранее спасибо

...