Как получить уведомление по идентификатору отправителя в FCM

Как получить уведомление по идентификатору отправителя в FCM.

Я пытаюсь получить уведомление, используя идентификатор отправителя в FCM, и у него также есть идентификатор устройства, и отправка на стороне сервера прошла успешно, но я не могу получить уведомление. Как решить вопрос. Я провел много исследований и не могу найти никакого решения. Ниже мой код.

java

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        if ( true) {
            scheduleJob();
        } else {
            // Handle message within 10 seconds
            handleNow();
        }
    }
    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }
}
// [END receive_message]

/**
 * Schedule a job using FirebaseJobDispatcher.
 */
private void scheduleJob() {
    // [START dispatch_job]
    FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new 
    GooglePlayDriver(this));
    Job myJob = dispatcher.newJobBuilder()
            .setService(MyJobService.class)
            .setTag("my-job-tag")
            .build();
    dispatcher.schedule(myJob);
    // [END dispatch_job]
}

/**
 * Handle time allotted to BroadcastReceivers.
 */
private void handleNow() {
    Log.d(TAG, "Short lived task is done.");
}

/**
 * Create and show a simple notification containing the received FCM 
 message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    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);

    String channelId = getString(R.string.default_notification_channel_id);
    Uri defaultSoundUri= 
    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("FCM Message")
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

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

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

comment
Должна быть проблема с конфигурацией Firebase. Чтобы настроить обмен сообщениями в облаке из студии Android, выполните следующие действия. Tools>Firebase>Cloud Messaging>Setup Firebase cloud messaging   -  person Paresh P.    schedule 13.12.2017


Ответы (3)


Пожалуйста, вызовите метод sendNotification () там, где вы хотите его использовать -

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        if ( true) {
            scheduleJob();
            sendNotification("YourMessage")

        } else {
            // Handle message within 10 seconds
            handleNow();
        }
    }
    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }
}
// [END receive_message]

/**
 * Schedule a job using FirebaseJobDispatcher.
 */
private void scheduleJob() {
    // [START dispatch_job]
    FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
    Job myJob = dispatcher.newJobBuilder()
            .setService(MyJobService.class)
            .setTag("my-job-tag")
            .build();
    dispatcher.schedule(myJob);
    // [END dispatch_job]
}

/**
 * Handle time allotted to BroadcastReceivers.
 */
private void handleNow() {
    Log.d(TAG, "Short lived task is done.");
}

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    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);

    String channelId = getString(R.string.default_notification_channel_id);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("FCM Message")
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
person Shivam Oberoi    schedule 13.12.2017

вы забыли вызвать метод sendNotification() в onMessageReceived(). вызовите этот метод для отправки уведомления.

person Dharmishtha    schedule 13.12.2017

вы забыли вызвать метод sendNotification().

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        if ( true) {
            scheduleJob();
            sendNotification("YourMessage")

        } else {
            // Handle message within 10 seconds
            handleNow();
        }
    }
    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }
}
// [END receive_message]

/**
 * Schedule a job using FirebaseJobDispatcher.
 */
private void scheduleJob() {
    // [START dispatch_job]
    FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
    Job myJob = dispatcher.newJobBuilder()
            .setService(MyJobService.class)
            .setTag("my-job-tag")
            .build();
    dispatcher.schedule(myJob);
    // [END dispatch_job]
}

/**
 * Handle time allotted to BroadcastReceivers.
 */
private void handleNow() {
    Log.d(TAG, "Short lived task is done.");
}

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    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);

    String channelId = getString(R.string.default_notification_channel_id);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("FCM Message")
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
person Ratilal Chopda    schedule 13.12.2017