fcm token что это такое

What is FCM token in Firebase?

In the new Firebase, under Notification, they have mentioned that developer can send notification to a particular device. For that, in console it asks for an FCM token. What is it exactly and how can I get that token?

5 Answers 5

What is it exactly?

An FCM Token, or much commonly known as a registrationToken like in google-cloud-messaging. As described in the GCM FCM docs:

An ID issued by the GCM connection servers to the client app that allows it to receive messages. Note that registration tokens must be kept secret.

How can I get that token?

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you’ll need to access this token.

You can access the token’s value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

The onTokenRefreshcallback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token. FirebaseInstanceID.getToken() returns null if the token has not yet been generated.

After you’ve obtained the token, you can send it to your app server and store it using your preferred method. See the Instance ID API reference for full detail on the API.

Источник

Best practices for FCM registration token management

If you use FCM APIs to build send requests programmatically, you may find that, over time, you are wasting resources by sending messages to inactive devices with stale registration tokens. This situation can affect the message delivery data reported in the Firebase console or data exported to BigQuery, showing up as a dramatic (but not actually valid) drop in delivery rates. This guide discusses some measures you can take to help ensure efficient message targeting and valid delivery reporting.

Читайте также:  Что значит фамилия марченко

Basic best practices

There are some fundamental practices you should follow in any app that uses FCM APIs to build send requests programmatically. The main best practices are:

Retrieve and store registration tokens

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. This is the token that you must include in targeted send requests from the API, or add to topic subscriptions for targeting topics.

As noted in our client setup guides, your app should retrieve this token at initial startup and save it to your app server alongside a timestamp. This timestamp must be implemented by your code and your servers, as it is not provided for you by FCM SDKs.

Also, it’s important to save the token to the server and update the timestamp whenever it changes, such as when:

Detect invalid token responses from the FCM backend

Make sure to detect invalid token responses from FCM and respond by deleting from your system any registration tokens that are known to be invalid. With the HTTP v1 API, these error messages may indicate that your send request targeted stale or invalid tokens:

See ErrorCodes for more information.

If you receive either of these responses for a targeted token, it is safe to delete your record of this token, since it will never again be valid. However, keep in mind that there will still be cases where a token is in fact invalid, but there is no indication of it. For example, sometimes the FCM backend cannot verify whether or not a device has gone offline permanently.

Ensuring registration token freshness

Determining whether a token is fresh or stale is not always straightforward. To cover all cases, you should adopt a threshold for when you consider tokens stale; our recommendation is two months. Any token older than two months is likely to be an inactive device; an active device would have otherwise refreshed its token.

Читайте также:  с какими вопросами обращаются к эндокринологу взрослому

Update tokens on a regular basis

We recommend that you periodically retrieve and update all registration tokens on your server. This requires you to:

Whatever timing pattern you follow, make sure to update tokens periodically. An update frequency of once per month likely strikes a good balance between battery impact vs. detecting inactive registration tokens. By doing this refresh, you also ensure that any device which goes inactive will refresh its registration when it becomes active again. There is no benefit to doing the refresh more frequently than weekly.

Unsubscribe stale tokens from topics

Managing topics subscriptions to remove stale registration tokens is another consideration. It involves two steps:

The benefit of these two steps is that your fanouts will occur faster since there are fewer stale tokens to fan out to, and your stale app instances will automatically resubscribe once they are active again.

Measuring delivery success

Generally, we advise targeting messages based on actions observed or captured from actively used app instances. This is especially important if you regularly send messages to topics with large numbers of subscribers; if a portion of those subscribers are actually inactive, the impact on your delivery statistics can be significant over time.

Before targeting messages to a token, consider:

For more information about delivery, see Understanding message delivery.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Что такое токен FCM в Firebase?

В новой Firebase в разделе Уведомления они упомянули, что разработчик может отправлять уведомления на определенное устройство. Для этого в консоли запрашивается токен FCM. Что это такое и как я могу получить этот токен?

Идентификатор, выданный серверами соединения GCM клиентскому приложению, который позволяет ему получать сообщения. Обратите внимание, что регистрационные токены должны храниться в секрете.

Как я могу получить этот токен?

При первом запуске приложения FCM SDK создает маркер регистрации для экземпляра клиентского приложения. Если вы хотите настроить таргетинг на отдельные устройства или создать группы устройств, вам потребуется доступ к этому токену.

Вы можете получить доступ к значению токена, расширив FirebaseInstanceIdService. Убедитесь, что вы добавили сервис в свой манифест, затем вызовите getToken в контексте onTokenRefresh и запишите значение, как показано:

Читайте также:  что делать если комп не видит блютуз наушники

OnTokenRefreshcallback срабатывает всякий раз, когда генерируется новый токен, поэтому вызов getToken в его контексте гарантирует вам доступ к текущему доступному регистрационному токену. FirebaseInstanceID.getToken () возвращает ноль, если токен еще не сгенерирован.

После того, как вы получили токен, вы можете отправить его на сервер приложений и сохранить его, используя ваш предпочтительный метод. См. Ссылку API идентификатора экземпляра для получения полной информации об API.

Вот простые шаги, чтобы добавить этот Gradle:

Никаких дополнительных разрешений не требуется в манифесте, как GCM. Не требуется приемник, чтобы проявить, как GCM. С FCM, com.google.Android.gms.gcm.GcmReceiver добавляется автоматически.

Перенесите службу прослушивателя

Это необходимо, если вы хотите

Добавить сервис в манифест

Для получения дополнительной информации посетите

FirebaseInstanceIdService больше не поддерживается. вы должны получить токен в методе onNewToken в FirebaseMessagingService.

У меня есть обновление о «токене Firebase Cloud Messaging», о котором я мог получить информацию.

Я действительно хотел знать об этом изменении, поэтому просто отправил письмо в службу поддержки. Токен Firebase Cloud Messaging вскоре снова вернется к ключу сервера. Там не будет ничего менять. Мы скоро увидим ключ сервера.

Они отказались от метода getToken () в приведенных ниже примечаниях к выпуску. Вместо этого мы должны использовать getInstanceId.

Чтобы обработать успех и неудачу в одном и том же слушателе, присоедините OnCompleteListener:

Кроме того, класс FirebaseInstanceIdService устарел, и он предложил метод onNewToken в FireBaseMessagingService в качестве замены для onTokenRefresh,

Источник

Сказочный портал