#android #firebase #notifications #firebase-cloud-messaging
# #Android #firebase #уведомления #firebase-облако-обмен сообщениями
Вопрос:
Есть ли какой-либо способ отправить уведомление пользователю, используя его адрес электронной почты или UID, используя панель управления Firebase Cloud Messaging (приложение для Android)?
Ответ №1:
Нет, для отправки push-уведомлений вам нужен токен fcm. Если вы не поддерживаете сопоставление идентификатора пользователя / электронной почты с токеном fcm, это невозможно
Ответ №2:
Для php вы можете использовать это обрезанное для отправки уведомлений пользователям
<?php
$tokens = array("yourFcmUserToken");
//you can add more to this array to send the message to multiple users, e.g. fetch an array of tokens from database
$message = array("message" => "This is message from Firebase");
$message_status = send_notification($tokens, $message);
echo "<br>".$message_status;
echo "<br>send: ".$message["message"]."<br>";
function send_notification ($tokens, $message){
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key=yourGoogleApiKey',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
и получите сообщение в приложении, как показано ниже
public class FirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FirebaseMessagingService";
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages
// are handled
// here in onMessageReceived whether the app is in the foreground or background. Data
// messages are the type
// traditionally used with GCM. Notification messages are only received here in
// onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated
// notification is displayed.
// When the user taps on the notification they are returned to the app. Messages
// containing both notification
// and data payloads are treated as notification messages. The Firebase console always
// sends notification
// messages. For more see: firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
Log.d(TAG, "From: " remoteMessage.getFrom());
Log.d(TAG, "Data: " remoteMessage.getData());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
//todo
//scheduleJob();
} else {
// Handle message within 10 seconds
//todo
//handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
}