我正在尝试检索firebase令牌,但是当我第一次运行该应用程序时,firebase令牌是无效的。我不知道为什么。当我第二次运行该应用程序时,我得到了令牌。我看到了另一个带有类似问题的帖子,但我不明白。
这是我的代码:
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String LOGTAG = "android-fcm";
@Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
storeTokenInPref(refreshedToken);
}
private void storeTokenInPref(String token) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("regId", token);
editor.apply();
}
我有一个片段,您可以在其中获得偏好的令牌,然后我想比较令牌是否在数据库内。
public class Profile extends Fragment implements MainActivity.OnBackPressedListener{
private View view;
private SharedPreferences preferences;
private String token;
private static final String LOGTAG = "android-fcm";
public Profile(){}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.profile, container, false);
((MainActivity) getActivity()).setOnBackPressedListener(this);
preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
displayFirebaseToken();
return view;
}
private void displayFirebaseToken() {
token = preferences.getString("regId", null);
Log.e(LOGTAG, "Firebase reg id: " + token);
if (!TextUtils.isEmpty(token)) {
SQLiteHelper database = new SQLiteHelper(getActivity(), "DB", null, 1);
List<Beacon> beaconList = database.getAllBeacons();
String classroom = "";
for (int i = 0; i < beaconList.size(); i++) {
if (beaconList.get(i).getId().equals(token)) {
classroom = beaconList.get(i).getClassroom();
break;
}
}
classroomTextView.setText(classroom);
}else {
System.out.println("Firebase token is not received yet!");
}
}
发生这种情况是因为ontokenrefresh((和storeTokenInpref((尚未在您尝试使用displayfirebasetoken((中使用该值的时候被调用。您需要等待使用令牌直到可用。通常,没有艰难的规则将需要多长时间,因为这取决于网络连接等因素。
尝试此
private void displayFirebaseToken() {
token = preferences.getString("regId", null);
if(token==null)
token = FirebaseInstanceId.getInstance().getToken();
Log.e(LOGTAG, "Firebase reg id: " + token);
if (!TextUtils.isEmpty(token)) {
SQLiteHelper database = new SQLiteHelper(getActivity(), "DB", null, 1);
List<Beacon> beaconList = database.getAllBeacons();
String classroom = "";
for (int i = 0; i < beaconList.size(); i++) {
if (beaconList.get(i).getId().equals(token)) {
classroom = beaconList.get(i).getClassroom();
break;
}
}
classroomTextView.setText(classroom);
}else {
System.out.println("Firebase token is not received yet!");
}
由于您试图通过方法OntokenRefresh((方法保存设备令牌,直到令牌将需要刷新,因此您需要使用`
''FirebaseInstanceId.getInstance().getToken();
通过使用此代码段,您可以在应用中获取设备令牌的任何位置
`