Android-приложение не показывает всплывающее уведомление, отправленное из облачных функций - PullRequest
0 голосов
/ 31 августа 2018

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

Мой index.js для развертывания в firebase:

'use strict' 
const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((data, context) => { 

const user_id = context.params.user_id; 
const notification_id = context.params.notification_id; 

console.log('We have a notification to send to: ', user_id); 

const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');

return deviceToken.then(result=>{
const token_id=result.val();

const payload={
notification:{
title: "FRiend Request",
body: "You have received a friend request",
icon:"default"}
};    

return admin.messaging().sendToDevice(token_id,payload).then(response =>{
console.log('This was notification feature');
return true;});
}); 
});

И на консоли функции firebase (по-прежнему отправлено уведомление)

My Firebase Console Function

1 Ответ

0 голосов
/ 31 августа 2018

Вам нужен класс службы обмена сообщениями Firebase.

создайте класс с именем MyFirebaseMessagingService, который получит уведомление и расшифрует его.

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCM Service";
    private static final String CHANNEL_ID = "MyFirebaseMessagingService";

    String title;
    String message;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO: Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated.

        title = "You have a new notification";
        message = remoteMessage.getNotification().getBody();
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("You have a new notification")
                .setContentText(remoteMessage.getNotification().getBody());


        int notificationId = (int) System.currentTimeMillis();
        // Issue the notification.

        NotificationManager notification = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        assert notification != null;
        notification.notify(notificationId, mBuilder.build());


        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(notificationId, mBuilder.build());

        createNotificationChannel();

        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());


    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = title;
            String description = message;
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);


            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            assert notificationManager != null;
            notificationManager.createNotificationChannel(channel);
        }
    }

    }

Добавьте метаданные внутри вашего Manifest.xml, как следующие

        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@mipmap/ic_launcher" />

Также добавьте следующую службу сообщений в ваш xml

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