Как реализовать метод отправки токена Firebase на сервер
Приложение получает токен firebase и необходимо как то отправить его на сервер данного приложения
Как можно это организовать? Как реализовать данный метод, например sendRegistrationToServer()?
public class TestFirebaseMessagingService extends TestMessagingService {
private static final String TAG = "TestFirebaseMessaging";
/**
* 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: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
/*
Существует два типа сообщений: сообщения данных и сообщения уведомлений. Сообщения данных обрабатываются здесь в
onMessageReceived независимо от того, находится ли приложение на переднем плане или в фоновом режиме.
Сообщения данных-это тип, традиционно используемый в GCM. Уведомления принимаются только здесь, в onMessageReceived,
когда приложение находится на переднем плане. Когда приложение находится в фоновом режиме,
отображается автоматически сгенерированное уведомление. Когда пользователь нажимает на уведомление,
они возвращаются в приложение. Сообщения, содержащие как уведомления, так и полезные нагрузки данных,
рассматриваются как сообщения уведомления. Консоль Firebase всегда отправляет уведомления. Подробнее см.:
https://firebase.google.com/docs/cloud-messaging/concept-options
*/
// TODO(developer): Handle FCM messages here.
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());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(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.
}
// [END receive_message]
/**
* Create and showChat a simple notification containing the received FCM message.
*
* messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, ActivitySplesh_.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)
.setSmallIcon(R.drawable.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());
}
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e(TAG, " ===> New firebase token " + s);
getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", s).apply();
Settings.firebaseToken = s;
cmdFirebaseTokenSend
.create(s)
.exec();
sendRegistrationToServer(s);
}
public static String getToken(Context context) {
return context.getSharedPreferences("_", MODE_PRIVATE).getString("fb", "empty");
}
private void sendRegistrationToServer(String token) {
}
}