I have converted a project from GCM to FCM but onTokenRefresh() function not call.
I have followed this link : https://developers.google.com/cloud-messaging/android/android-migrate-fcm
I have completed follow step
- Add Firebase project and add application with SHA1 key
- Remove all code of GCM from my android project
- Add FCM code
FCM Code:
In manifest.xml
<service android:name=".Commonclass.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".Commonclass.MyFirebaseInstanceIDService" >
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
Create two java file MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
@Override
public void onTokenRefresh() {
Log.d(TAG, "Refreshed token start");
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
GlobalClass.strDeviceToken = refreshedToken;
Log.e("token",GlobalClass.strDeviceToken);
Log.d(TAG, "Refreshed token end");
storeToken(refreshedToken);
}
private void storeToken(String token) {
//saving the token on shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(GlobalClass.SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(GlobalClass.prefFCMToen, token);
editor.apply();
}
}
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
//Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
Map<String, String> params = remoteMessage.getData();
JSONObject json = new JSONObject(params);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
}
I follow this google guidelines https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId every time I reinstall application but not call onTokenRefresh().
The
onTokenRefresh()
method doesn't necessarily get called every time the app starts or if it is newly installed. It only triggers on some scenarios (see my answer here).The implementation looks correct. In order to get the current token, you must first call
getToken()
somewhere similar to a MainActivity.The
getToken()
method can immediately return the current token or null. If its null, it means that the FCM server is not yet finished generating or sending the token back to the client, in which caseonTokenRefresh()
would trigger upon completion.