Hope all of you aware of this class, used to get notification token whenever firebase notification token got refreshed we get the refreshed token from this class, From follo
firebaser here
Check the reference documentation for FirebaseInstanceIdService:
This class was deprecated.
In favour of overriding
onNewToken
inFirebaseMessagingService
. Once that has been implemented, this service can be safely removed.
Weirdly enough the JavaDoc for FirebaseMessagingService
doesn't mention the onNewToken
method yet. It looks like not all updated documentation has been published yet. I've filed an internal issue to get the updates to the reference docs published, and to get the samples in the guide updated too.
In the meantime both the old/deprecated calls, and the new ones should work. If you're having trouble with either, post the code and I'll have a look.
Simply call this method to get the Firebase Messaging Token
public void getFirebaseMessagingToken ( ) {
FirebaseMessaging.getInstance ().getToken ()
.addOnCompleteListener ( task -> {
if (!task.isSuccessful ()) {
//Could not get FirebaseMessagingToken
return;
}
if (null != task.getResult ()) {
//Got FirebaseMessagingToken
String firebaseMessagingToken = Objects.requireNonNull ( task.getResult () );
//Use firebaseMessagingToken further
}
} );
}
The above code works well after adding this dependency in build.gradle file
implementation 'com.google.firebase:firebase-messaging:21.0.0'
Note: This is the code modification done for the above dependency to resolve deprecation. (Working code as of 1st November 2020)
In KOTLIN:- If you want to save Token into DB or shared preferences then override onNewToken in FirebaseMessagingService
override fun onNewToken(token: String) {
super.onNewToken(token)
}
Get token at run-time,use
FirebaseInstanceId.getInstance().instanceId
.addOnSuccessListener(this@SplashActivity) { instanceIdResult ->
val mToken = instanceIdResult.token
println("printing fcm token: $mToken")
}
Yes FirebaseInstanceIdService is deprecated
FROM DOCS :- This class was deprecated. In favour of
overriding onNewToken
inFirebaseMessagingService
. Once that has been implemented, this service can be safely removed.
No need to use FirebaseInstanceIdService
service to get FCM token You can safely remove FirebaseInstanceIdService
service
Now we need to @Override onNewToken
get Token
in FirebaseMessagingService
SAMPLE CODE
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onNewToken(String s) {
Log.e("NEW_TOKEN", s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
Log.e("JSON_OBJECT", object.toString());
String NOTIFICATION_CHANNEL_ID = "Nilesh_channel";
long pattern[] = {0, 1000, 500, 1000};
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(pattern);
notificationChannel.enableVibration(true);
mNotificationManager.createNotificationChannel(notificationChannel);
}
// to diaplay notification in DND Mode
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = mNotificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID);
channel.canBypassDnd();
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage.getNotification().getBody())
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true);
mNotificationManager.notify(1000, notificationBuilder.build());
}
}
You need to register your
FirebaseMessagingService
in manifest file like this
<service
android:name=".MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
.getToken(); is also deprecated if you need to get token in your activity than Use getInstanceId ()
Now we need to use getInstanceId () to generate token
getInstanceId ()
Returns the ID
and automatically generated token for this Firebase
project.
This generates an Instance ID if it does not exist yet, which starts periodically sending information to the Firebase backend.
Returns
InstanceIdResult
which holds the ID
and token
.SAMPLE CODE
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MyActivity.this, new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String newToken = instanceIdResult.getToken();
Log.e("newToken",newToken);
}
});
Here is the working code for kotlin
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(p0: String?) {
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val NOTIFICATION_CHANNEL_ID = "Nilesh_channel"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications", NotificationManager.IMPORTANCE_HIGH)
notificationChannel.description = "Description"
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.vibrationPattern = longArrayOf(0, 1000, 500, 1000)
notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
}
// to diaplay notification in DND Mode
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID)
channel.canBypassDnd()
}
val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
notificationBuilder.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage!!.getNotification()!!.getBody())
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true)
notificationManager.notify(1000, notificationBuilder.build())
}
}
FCM implementation Class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
if(data != null) {
// Do something with Token
}
}
}
// FirebaseInstanceId.getInstance().getToken();
@Override
public void onNewToken(String token) {
super.onNewToken(token);
if (!token.isEmpty()) {
Log.e("NEW_TOKEN",token);
}
}
}
And call its initialize in Activity or APP :
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
instanceIdResult -> {
String newToken = instanceIdResult.getToken();
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.i("FireBaseToken", "onFailure : " + e.toString());
}
});
AndroidManifest.xml :
<service android:name="ir.hamplus.MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
**If you added "INSTANCE_ID_EVENT" don't forget to disable it.
And this:
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
suppose to be solution of deprecated:
FirebaseInstanceId.getInstance().getToken()
EDIT
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
can produce exception if the task is not yet completed, so the method witch Nilesh Rathod described (with .addOnSuccessListener
) is correct way to do it.
Kotlin:
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
val newToken = instanceIdResult.token
Log.e("newToken", newToken)
}