Уведомления Firebase Messaging не приходят, хотя база данных правильно ссылается - PullRequest
0 голосов
/ 24 апреля 2019

Я недавно начал изучать Firebase и его возможности, и я очень впечатлен тем, насколько легко это реализовать. Но я сталкиваюсь с очень забавной проблемой. Я пытался использовать функции Firebase для отправки уведомлений конкретному пользователю, когда данные записываются в базу данных в реальном времени. Я прочесал весь интернет, чтобы найти решение, но все равно ничего не получил. Даже журналы на вкладке функций не отображаются. Я думаю, что я не вижу что-то. Пожалуйста помоги.

index.js

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

admin.initializeApp();

exports.sendNotification = functions.database.ref('/Hotel_Complaints/Users/{usersId}/')
.onWrite((change,context) =>{

var user_id = context.params.usersId;
console.log(user_id);
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = change.after.val();

var device_token = admin.database().ref('/Hotel_Staff/'+user_id+'/device_token').once('value');

return device_token.then(result => {

var token_id = result.val();

console.log(token_id);

var str = eventSnapshot.issue_description;

var payload = {
    notification: {
        title: eventSnapshot.staff_name,
        body: str,

    }   

};

// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToDevice(token_id, payload).then(function (response) {
        // See the MessagingTopicResponse reference documentation for the
        // contents of response.
        console.log("Successfully sent message:", response);
        return;
    })
    .catch(function (error) {
        console.log("Error sending message:", error);
    });

});

});

FirebaseMessagingService.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

        String info_body = remoteMessage.getNotification().getBody();
        String info_title = remoteMessage.getNotification().getTitle();
        String click_action = "Home";

        showNotification(info_body, info_title, click_action);



}

private void showNotification(String info_body, String info_title, String click_action) {
    Intent intent;
    switch (click_action) {
        case "Home":
            intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            break;
        default:
            intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            break;

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

    int notificationId = 1;
    String channelId = "channel-01";
    String channelName = "Channel Name";
    String GROUP_KEY_WORK_EMAIL = "com.softwaremongul.reporttrackingsystem";
    int importance = NotificationManager.IMPORTANCE_HIGH;

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(
                channelId, channelName, importance);
        assert notificationManager != null;
        notificationManager.createNotificationChannel(mChannel);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_stat_name)
            .setContentTitle(info_title)
            .setContentText(info_body)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setGroup(GROUP_KEY_WORK_EMAIL)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(info_body));

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntent(intent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
            0,
            PendingIntent.FLAG_UPDATE_CURRENT
    );
    mBuilder.setContentIntent(resultPendingIntent);

    notificationManager.notify(notificationId, mBuilder.build());


}

}

И, наконец, база данных СНАПШОТ

Функции журнала консоли

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...