Effective interaction with mobile devices is impossible without a reliable communication channel, and it is unique identifiers that allow notifications and data to be delivered exactly to the target. Obtaining a device token is a fundamental step in setting up any modern application that plans to use Google cloud services. Without this key, the server part simply will not know where to send data packets, which will make the entire push notification architecture inoperable.

In this article we will analyze in detail the process of generating a token, starting from connecting libraries and ending with programmatic extraction of a unique identifier. We will look at the nuances of working with Firebase Cloud Messagingas this is the current industry standard, replacing outdated solutions. Understanding how tokens work will allow you to avoid common mistakes during integration and ensure stable operation of your software product.

What is a device token and why do you need it?

A registration token is a unique string of characters that is assigned to a specific instance of an application on a specific device. This identifier acts as an address in a vast network of mobile gadgets, allowing the server to distinguish one phone from a million others. When a user installs an application, Google's servers generate this key and pass it on to the client for further use.

The main function of the token is to route messages through the infrastructure. Google Play Services. If you are developing a notification system, then this is the code that will be used as the destination in requests to the API. Without a correctly received and stored token, it is impossible to implement personalized distribution or data synchronization in the background.

It is worth noting that a token is not a static value fixed forever. It may change if you reinstall the app, clear your data, or update your security tokens on Google's servers. Therefore, your system must be ready to handle update events and always store the current value in the database.

โš ๏ธ Warning: Never use a single device token to send test messages on a production server. This may result in account suspension due to suspicious activity or API violations.

๐Ÿ’ก

Always store the token in conjunction with the user ID in your database. This will allow you to quickly find a specific personโ€™s device if problems arise with delivery.

Preparing the project and connecting Firebase

The first step towards obtaining a token is to correctly configure the development environment and link the project to the Firebase console. You need to create a new project in the Firebase Console web interface and add an Android application to it, specifying the exact package ID (Application ID). After registering the application, you will receive a configuration file, which is the key to integration.

The downloaded file google-services.json must be placed in the directory app of your Android Studio project. This file contains critical metadata, including project IDs and API keys needed to authorize requests. Without it, the project build will be successful, but the runtime libraries will not be able to initialize the connection to Google servers.

Next you need to configure the Gradle build files. In the root file build.gradle (Project level) you need to add a dependency for the Google Services plugin. The dependency of the Firebase Messaging library itself is added to the file build.gradle (App level). Only after completing these steps will the project be ready to work with cloud messages.

โ˜‘๏ธ Preparing the project to work with tokens

Done: 0 / 4

Check that the connection is correct by synchronizing the project. If the build logs do not contain errors related to missing resources or incorrect versions of libraries, you can proceed to writing code. Errors at this stage are often associated with incompatible library versions or incorrectly specified path to the configuration file.

Programmatically obtaining a token via FirebaseMessaging

The most modern and recommended way to obtain a token is to use asynchronous class methods FirebaseMessaging. In new versions of the SDK, the method getToken returns an object Task<String>which requires the use of lambda expressions or anonymous classes to process the result. This approach ensures that you get an up-to-date token, even if it was previously generated.

To retrieve the value, you must call a method at the appropriate place in the activity or service lifecycle. This is usually done in the main screen method or in a custom class that inherits from onCreate main screen or in a custom class that inherits FirebaseMessagingService. The code must be wrapped in exception handling, as the process of retrieving the token may take time or fail if there is no network.

FirebaseMessaging.getInstance.getToken

.addOnCompleteListener(new OnCompleteListener<String> {

@Override

public void onComplete(@NonNull Task<String> task) {

if (!task.isSuccessful) {

Log.w("TAG","Fetching FCM registration token failed", task.getException);

return;

}

String token = task.getResult;

Log.d("TAG","Token:" + token);

}

});

The resulting token string must be immediately sent to your backend server. Storing the token locally is acceptable for caching purposes, but the primary source of truth should remain your backend database. This will allow you to manage the user's list of active devices and clear it if necessary. SharedPreferences valid for caching, but the primary source of truth should remain your backend database. This will allow you to manage the user's list of active devices and clear it if necessary.

๐Ÿ’ก

The getToken method returns a Promise (Task), so be sure to wait for the operation to complete before using the result. A synchronous call is not possible.

Alternative methods and working with Instance ID

Previously, a class was used to obtain identifiers InstanceId, which is now considered deprecated, but can still be found in legacy code. Understanding the difference between the old and new approach is important to support existing projects. In older implementations, the token was often obtained through a method getToken(senderId, scope)where it was necessary to explicitly specify the sender and scope.

In some specific cases, developers turn to the Advertising ID or other system identifiers in an attempt to replace the Firebase token with them. This is a wrong strategy, since GAID (Google Advertising ID) is intended for advertising purposes and can be reset by the user in the privacy settings at any time. The FCM token is tied to the application installation and is more stable for functional purposes.

If your application is running in an environment without Google services (for example, some Huawei devices or emulators without GMS), the standard method of obtaining the token will return an error. In such cases, it is necessary to implement alternative communication channels or use third-party push services, such as Huawei Push Kit, which require separate integration and receipt of their own tokens.

Receipt method Status Dependency Reliability
FirebaseMessaging.getToken Current Google Play Services High
InstanceId.getToken Outdated Google Play Services Medium
Advertising ID Not recommended Google Play Services Low (reset)
Android ID System Android OS Medium (changes on reset)
Why is InstanceId deprecated?

The InstanceId class has been merged with the Firebase Messaging functionality to simplify the API. Now all operations with tokens are managed through a single FirebaseMessaging interface, which reduces the likelihood of configuration errors.

Token refresh and reset processing

The life cycle of a token does not end when it is received. The Android system and Google servers may initiate token rotation for various reasons, such as security keys being compromised or an extended period of inactivity. Your application must be ready to intercept these events and update the record on the server automatically.

To do this, you need to override the method onNewToken in the class that inherits FirebaseMessagingService. This method is called by the system whenever the token changes. Ignoring this event will result in you continuing to send notifications to the old, no longer valid address, which will cause delivery errors.

Inside the method onNewToken you should immediately send the new value to your server. You shouldn't rely on the user opening the app and triggering the standard method to get a token. A background service ensures that the update occurs regardless of whether the application interface is currently running.

โš ๏ธ Note: APIs and token methods may be updated by Firebase developers. Always check the official documentation before starting a new integration to ensure that you use the latest versions of the libraries.

๐Ÿ“Š What aspect of working with tokens do you most often have difficulty with?
Setting up Gradle
Getting a token in code
Processing onNewToken
Sending to the server
Other

Diagnostics of problems and common errors

The process of obtaining a token does not always go smoothly, and developers often encounter exceptions in the logs. The most common error is FirebaseException: MISSING_INSTANCEID_SERVICE, which indicates the lack of necessary Google Play services on the device. This often occurs on emulators without a GMS image or on specific firmware from Chinese manufacturers.

Another common problem is an error INVALID_SENDERthat occurs when the Sender ID in the code and in the configuration file does not match. Make sure that the project number specified in google-services.jsonis the same as the one you use during initialization if you do it manually. Inconsistency between library versions can also lead to strange behavior where the token is simply not generated.

For debugging, use fine-grained logging. Enable debug mode in Android Studio and monitor the system log when the application is launched. If the token is not returned within 10-15 seconds, there is most likely a problem with the network connection or Google's firewall blocking the domains.

If you are using a proxy or corporate network, make sure the ports for SSL connections are open. Firebase services require stable internet access to generate tokens, and any interruptions at the network level will be interpreted as a service failure.

๐Ÿ’ก

When testing on an emulator, be sure to select a system image labeled "Google APIs" or "Google Play", otherwise Firebase services will not be able to initialize correctly.

Frequently asked questions questions (FAQ)

Can I get a token without an Internet connection?

No, to generate a new token an active connection to Google servers is required. However, if the token has already been received earlier and cached in the system, the method getToken can return it from local storage instantly, but the initial generation is always online.

How long does an Android token live?

The token does not have a strict expiration date in days or hours. It remains in effect until it is revoked by the server, the application's security key is changed, or the user deletes the application. On average, tokens live for months, but you canโ€™t rely on them to last forever.

What if getToken returns null?

The method returns a Task, so null as a result means an execution error. Check the exception log attached to the task. Most often, the reason is the lack of Google Play Services, an incorrect SHA-1 fingerprint in the Firebase console, or a network block.

Can one token be used for multiple applications?

No, the token is unique for the Application-Device pair. Even if two applications are installed on the same phone and use the same Firebase project, each of them will have its own unique registration token.