FirebaseInstanceIdService已经被弃用。

293

希望大家都知道这个类,它用于在 firebase 通知令牌刷新时获取通知令牌。我们可以从下面的方法中获取刷新后的令牌。

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);
}
为了使用我想要实现 FCM,我从 FirebaseInstanceIdService 扩展了 MyClass。
但是,显示出 FirebaseInstanceIdService 被弃用
有人知道吗?我应该使用哪个方法或类来获取刷新的令牌,因为这已经被弃用了。
我正在使用:implementation 'com.google.firebase:firebase-messaging:17.1.0' 我检查了同样的文档,没有提到这一点:FCM 配置文档 更新:
此问题已得到解决。
由于 Google 弃用了 FirebaseInstanceService,我问了这个问题以找到方法,我知道我们可以从 FirebaseMessagingService 中获取 Token,
之前,当我提出这个问题时,文档没有更新,但现在 Google 文档已经更新,所以更多信息,请参阅此 Google 文档:FirebaseMessagingService 旧的:FirebaseInstanceService(已弃用)
@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);
}

来自:FirebaseMessagingService的新功能

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Log.d("NEW_TOKEN",s);
}

1
GitHub 上进行了交叉发布。 - Rosário Pereira Fernandes
需要/正确调用super.onNewToken(s);吗?(我在https://firebase.google.com/docs/cloud-messaging/android/client上没有看到它被调用。) - ban-geoengineering
清单文件会有任何更改吗? - Muahmmad Tayyib
1
你只需要在清单文件中不再定义FirebaseInstanceService,因为它已经被弃用。 - Uttam Panchasara
2
谢谢。Android Studio需要更新Firebase设置向导中的说明。 - John Gorenfeld
显示剩余3条评论
19个回答

183

2020年11月12日更新

现在FirebaseInstanceId也已经被弃用。

我们现在需要使用FirebaseMessaging.getInstance().token

示例代码

        FirebaseMessaging.getInstance().token.addOnCompleteListener {
            if(it.isComplete){
                firebaseToken = it.result.toString()
                Util.printLog(firebaseToken)
            }
        }

    

是的FirebaseInstanceIdService已被弃用

来自文档:- 已经弃用了这个类。 改用在FirebaseMessagingService中覆盖onNewToken。 一旦实现了这个,就可以安全地删除此服务。

无需使用FirebaseInstanceIdService服务获取FCM令牌,您可以安全地将其删除。

现在,我们需要@Override onNewTokenFirebaseMessagingService中获得Token

示例代码

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());
    }
}

#编辑

您需要像这样在清单文件中注册您的FirebaseMessagingService

    <service
        android:name=".MyFirebaseMessagingService"
        android:stopWithTask="false">
        <intent-filter>
            
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

#如何在您的Activity中获取令牌

.getToken();已弃用,如果您需要在Activity中获取令牌,请使用getInstanceId()

现在我们需要使用getInstanceId()来生成令牌

getInstanceId()返回此Firebase项目的ID和自动生成令牌

如果尚不存在实例ID,则会生成一个实例ID,该ID开始定期发送信息到Firebase后端。

返回值

  • 任务,您可以使用它通过InstanceIdResult查看结果,其中包含IDtoken

示例代码

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MyActivity.this,  new OnSuccessListener<InstanceIdResult>() {
     @Override
     public void onSuccess(InstanceIdResult instanceIdResult) {
           String newToken = instanceIdResult.getToken();
           Log.e("newToken",newToken);

     }
 });

##编辑2

这里是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())

    }
}

1
评论不适合进行长时间的讨论;此对话已被移至聊天室 - Samuel Liew
为什么没有人展示如何导入FirebaseMessagingService? - temirbek
嗨,我必须使用FirebaseInstallations还是FirebaseMessaging? - Тони
@Tony 目前我正在使用 FirebaseMessaging.getInstance() - AskNilesh
2
这个回答应该被接受,以帮助其他人找到已弃用的问题。许多文章仍然使用FirebaseInstanceId来获取新的FCM令牌。希望其他人能看到我的评论。 - Yohanim
onNewToken方法已被移除 - Amit Vaghela

151

火基础工程师在此

查看FirebaseInstanceIdService参考文档

这个类已经被弃用。

建议重写FirebaseMessagingService中的onNewToken方法。一旦实现了这个方法,就可以安全地删除这个服务。

奇怪的是,FirebaseMessagingService的JavaDoc并没有提到onNewToken方法。看起来并不是所有更新的文档都已经发布了。我已经提交了一个内部问题,以便更新参考文档,并将指南中的示例更新。

同时,旧/弃用调用和新调用都应该有效。如果您遇到任何问题,请发布代码,我会检查一下。


9
Firebase文档目前尚未更新。 - Rosário Pereira Fernandes
1
是的@frank,方法确实存在,但相关文档尚未更新。 - Uttam Panchasara
@kev,听起来像是一个(有效的)新问题。请创建一个新的帖子,并提供一个最小完整的代码片段。 - Frank van Puffelen
@FrankvanPuffelen已经完成了。瞧一瞧。https://dev59.com/wVUK5IYBdhLWcg3wySXA#51296330 - kev
1
我也发现了 Xamarin Android 的这个更新。在扩展 FirebaseMessagingService 类的类中添加了 OnNewToken 方法。但是该方法没有被调用。我无法弄清楚应该怎么做。在 Xamarin 中,Android Manifest 文件是否有所不同? - Prabesh

16

只需调用此方法即可获取Firebase消息令牌。

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
                    }
                } );
    }

在 build.gradle 文件中添加此依赖项后,上述代码将正常工作。

implementation 'com.google.firebase:firebase-messaging:21.1.0'

注意: 这是对上述依赖项进行代码修改以解决弃用问题的结果。(截至2021年5月9日的工作代码)


2
嗨,我必须使用 FirebaseInstallations 还是 FirebaseMessaging? - Тони
1
嗨@Tony,要通过Firebase发送云消息,必须使用“firebase-messaging”。看起来“firebase-installations”没有提供完整的令牌,这是发送云消息到其他设备所需的。如果我错了,请纠正我。谢谢! - niranj1997

14

还有这个:

FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()

假设是“deprecated”的解决方案:

FirebaseInstanceId.getInstance().getToken()

编辑

FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()如果任务尚未完成,则可能会产生异常,因此Nilesh Rathod所描述的方法(使用.addOnSuccessListener)是正确的方法。

Kotlin:

FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
        val newToken = instanceIdResult.token
        Log.e("newToken", newToken)
    }

7

FirebaseInstanceIdService已经被弃用,需要使用“FirebaseMessagingService”。

请查看下面的图片:

enter image description here

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("NEW_TOKEN",s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }
}

5

Kotlin可以让代码变得更加简单,比其他答案展示的代码还要简单。

为了在token刷新时获取新的token:

class MyFirebaseMessagingService: FirebaseMessagingService() {

    override fun onNewToken(token: String?) {
        Log.d("FMS_TOKEN", token)
    }
    ...
}

在运行时从任何地方获取令牌:

FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener {
    Log.d("FMS_TOKEN", it.token)
}

4

在 Kotlin 中:如果您想将令牌保存到数据库或共享首选项中,则需要在FirebaseMessagingService中重写 onNewToken。

override fun onNewToken(token: String) {
        super.onNewToken(token)
    }

在运行时获取令牌,使用

FirebaseInstanceId.getInstance().instanceId
                        .addOnSuccessListener(this@SplashActivity) { instanceIdResult ->
                            val mToken = instanceIdResult.token
                            println("printing  fcm token: $mToken")
                        }

现在是 override fun onNewToken(token: String)(没有问号)。 - Csaba Toth

4

FCM 实现类:

 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);
 }
}
}

并在 Activity 或 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>

如果您添加了“INSTANCE_ID_EVENT”,请不要忘记禁用它。


2

您需要使用 FirebaseMessagingService() 代替 FirebaseInstanceIdService


2

以下是C#/Xamarin.Android的解决方案:

var token = await FirebaseInstallations.Instance.GetToken(forceRefresh: false).AsAsync<InstallationTokenResult>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接