Уведомление об обмене сообщениями в облаке - PullRequest
0 голосов
/ 19 апреля 2020

Я новичок в облачной функции Firebase и fcm. Моя ситуация: всякий раз, когда в базе данных публикуется новая статья, мне нужно показать уведомление пользователю моего приложения.

Облачная функция Firebase работала отлично, но уведомление не получено устройством android.

функция облака

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


admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/Vacancy/{articleId}')
.onWrite((event: { after: any; }) => {
    console.log("Successfully sent message:2");
        var eventSnapshot = event.after;
        var str1 = "Author is ";
        var str = str1.concat(eventSnapshot.child("author").val());
        console.log(str);

        var topic = "android";
        var payload = {
            data: {
                title: eventSnapshot.child("title").val(),
                author: eventSnapshot.child("author").val()
            }
        };

        return admin.messaging().sendToTopic(topic, payload)
            .then(function (response: any) {

                console.log("Successfully sent message:", response);
            })
            .catch(function (error: any) {
                console.log("Error sending message:", error);
            });
        });

код манифеста

 <service
        android:name=".ServiceNotification.NotificationMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

код класса NotificationMessagingService

public class NotificationMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        FirebaseMessaging.getInstance().subscribeToTopic("android");

        if (remoteMessage.getData().size() > 0) {
            showNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("author"));
        }


        if (remoteMessage.getNotification() != null) {

        }
    }

    private void showNotification(String title, String author) {
        Intent intent = new Intent(this, HomeActivity.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("New Article: " + title)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("By " + author)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

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


}

облако журнал функций

1:33:46.257 AM
sendNotification
Successfully sent message:2
1:33:46.263 AM
sendNotification
Author is Raja
1:33:47.022 AM
sendNotification
Successfully sent message: { messageId: 5711725841493019000 }
1:33:47.040 AM
sendNotification
Function execution took 1005 ms, finished with status: 'ok'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...