Reputation: 35
How can I correct this block of code since FirebaseInstanceId is deprecated in Android Studio?
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
I tried to change it to this:
String refreshedToken = FirebaseMessaging.getInstance().getToken();
But when I do this, I get an error saying
Change variable 'refreshedToken' type to 'Task<String>'
My full code is:
import android.app.Application;
import androidx.multidex.MultiDexApplication;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
public class MyApplication extends MultiDexApplication {
@Override
public void onCreate() {
super.onCreate();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
FirebaseMessaging.getInstance().subscribeToTopic("fireblogappnotification");
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
}
}
Upvotes: 0
Views: 349
Reputation: 138969
You are getting the following error:
Change variable 'refreshedToken' type to 'Task'
Because you are trying to save an object of type Task<String>
into an object of type String, which is actually not possible in Java, and this is because there is no inheritance relationship between these two classes.
In order to get the token, you need to attach a listener. So please try the following lines of code:
Task<String> tokenTask = FirebaseMessaging.getInstance().getToken();
tokenTask.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (task.isSuccessful()) {
String token = task.getResult();
Log.d("TAG", "token: " + token);
//Do what you need to do with your token
}
}
});
Upvotes: 1
Reputation: 9073
It's giving you that error because FirebaseMessaging.getInstance().getToken();
has return type of Task<String>
& you're using String.
So what you can do is add listener & wait for task to complete & get token from that.
As following:
Task<String> refreshedToken = FirebaseMessaging.getInstance().getToken();
refreshedToken.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull @NotNull Task<String> task) {
if (task.isSuccessful()){
String token = task.getResult();
}
}
});
Upvotes: 1