我遇到了一个尝试从Firebase获取令牌()的问题,但是由于以下错误,我无法获取令牌:
Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.iid.FirebaseInstanceId.getInstanceId()' on a null object reference
答案 0 :(得分:0)
FirebaseInstanceId.getInstance()
已弃用
您可以在onNewToken()
函数中获得 firebase_token
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onNewToken(String s) {
super.onNewToken(s);
// s is your token
// Do whatever you want with it
// You can store it in SharedPreferences
}}
答案 1 :(得分:0)
我不确定,但是您必须在活动中初始化Firebase
FirebaseApp.initializeApp(您的活动);
答案 2 :(得分:0)
请检查是否在gradle文件中添加了此(com.google.firebase:firebase-messaging:17.3.4')依赖项。要获得更多帮助,您可以从here获得帮助。以及您是否希望以这种方式获取令牌。
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
答案 3 :(得分:0)
当我使用BUCK构建应用程序时遇到了同样的问题,但是当我使用Gradle构建应用程序时,我能够正确使用Firebase。您可能需要验证Firebase是否已初始化。如果是这样,您应该在日志中看到它:
I / FirebaseInitProvider:FirebaseApp初始化成功
在此处查看文档:{{3}},不赞成使用FirebaseInstanceId.getInstance()。getToken(),而推荐使用getInstanceId()。
相反,本文档显示了如何获取当前的Firebase令牌:https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
此文档说,令牌更新后,将调用onNewToken方法:https://firebase.google.com/docs/cloud-messaging/android/client?authuser=1#retrieve-the-current-registration-token
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
@Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(token);
}
使用Gradle,我可以将其与以下库一起使用:
implementation 'com.google.firebase:firebase-messaging:18.0.0' implementation 'com.google.firebase:firebase-auth:17.0.0'
我已经从GCM迁移到FCM,文档很简单,可以与Gradle一起使用:https://firebase.google.com/docs/cloud-messaging/android/client?authuser=1#monitor-token-generation
如果您使用Gradle进行构建,则本文档似乎也很简单:https://developers.google.com/cloud-messaging/android/android-migrate-fcm