问题描述
既然 getToken() 已弃用,我想知道获取 Firebase 令牌以发送推送通知的正确方法是什么.
I would like to know what would be the correct way to get Firebase token for sending push notification now that getToken() is deprecated.
推荐答案
更新的答案
FirebaseInstanceId 已弃用,但现在您可以使用 FirebaseMessaging.getInstance().token.
FirebaseInstanceId is deprecated but now you can use FirebaseMessaging.getInstance().token.
例如:
FirebaseMessaging.getInstance().token.addOnSuccessListener { result ->
if(result != null){
fbToken = result
// DO your thing with your firebase token
}
}
旧答案
作为文档 说:
此方法已被弃用.支持 getInstanceId().
getInstanceId() 将返回一个带有 InstanceIdResult 的任务.像这样:
getInstanceId() will return a Task with and InstanceIdResult. Like this:
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String deviceToken = instanceIdResult.getToken();
// Do whatever you want with your token now
// i.e. store it on SharedPreferences or DB
// or directly send it to server
}
});
虽然这种方法确实会取代 FirebaseInstanceId.getInstanceId().getToken() 的使用,但它并没有解决 FirebaseInstanceIdService 也被弃用的事实留给我们的另一个问题是:在哪里使用它?它可以在任何 Activity 上下文中使用,它将始终返回令牌.但是如果我们只想在创建和很少更新时获取令牌怎么办?为此,您应该覆盖我们旧的 FirebaseMessagingService 实现中的新方法 onNewToken:(是的,消息",而不是InstanceId")
Though is true that this approach will literally replace the use of FirebaseInstanceId.getInstanceId().getToken(), it does not solve the fact that FirebaseInstanceIdService is also deprecated leaving us with another question that is: where to use it?It can be used in any Activity context that it will always return the token. But what if we want to get the token only on creation and when it is rarely updated?For that you should override new method onNewToken from our old FirebaseMessagingService implementation:(Yes, "Messaging", not "InstanceId")
@Override
public void onNewToken(String s) {
super.onNewToken(s);
String deviceToken = s;
// Do whatever you want with your token now
// i.e. store it on SharedPreferences or DB
// or directly send it to server
}
这种方式的代码将保持精简,甚至不需要使用第一种方法.
This way code will remain leaner and wont even be necessary to use the first approach.
这篇关于由于 FirebaseInstanceId.getInstance().getToken() 已弃用,我现在应该使用什么方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!