Уведомление не всплывало после срабатывания функции firebase - PullRequest
0 голосов
/ 08 июня 2018

Я относительно новичок в Android Dev't и у меня проблема.Я пытался реализовать функции Firebase для отправки уведомлений в мое приложение для Android, когда определенные данные были сохранены в моей базе данных Firebase в реальном времени.Но после сохранения данных и выполнения функции в журналах говорится, что они успешно отправлены, но я не получаю никаких уведомлений на моем тестовом устройстве Android.В чем может быть проблема?Ниже приведен мой код.

Мой код JS.

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

admin.initializeApp();

exports.sendNotification = functions.database.ref('/Lecture_Materials/{MIS}/{MISId}/name')
.onWrite(( change,context) =>{

// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = change.after.val();
var str1 = "Lecture material uploaded is: " + eventSnapshot.name;
console.log(eventSnapshot);

var topic = "Management.Information.System";
var payload = {
    data: {
        name: str1,
    }
};

// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, 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);
    });
    });

Мой OnMessageReceived

package com.dreamlazerstudios.gtuconline;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

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

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        showNotification(remoteMessage.getData().get("name"));
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {

    }
}

private void showNotification(String name) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Lecture note uploaded is: " + name)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("Lecture Notes")
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}

Любая помощь очень ценится.

1 Ответ

0 голосов
/ 08 июня 2018

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

Вы можете проверить следующую документацию, чтобы увидеть, как реализовать Firebase Cloud Messaging на стороне клиента (также вы можете использовать инструмент помощника Firebase в Android Studio, его можно найти в Инструменты> Firebase ):

https://firebase.google.com/docs/cloud-messaging/android/client

Для отправки уведомления на стороне сервера вы можете следовать приведенному ниже руководству:

https://firebase.google.com/docs/cloud-messaging/admin/send-messages

Кроме того, вытакже можно использовать некоторые сторонние библиотеки, такие как:

https://www.npmjs.com/package/fcm-push

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