FirebaseInstanceIdService 中的 onTokenRefresh 仅在生成新令牌时调用。如果您的应用之前已安装并生成了令牌,则不会调用 onTokenRefresh。尝试卸载并重新安装应用程序以强制生成新令牌,这将导致 onTokenRefresh 被调用。
还要确保您的 FirebaseInstanceIdService 在您的 AndroidManifest.xml 中正确定义
在您的清单文件中。
<service
android:name="com.bnt.etailers.fcm.MyFireBaseInstanceIDService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name="com.bnt.etailers.fcm.GCMNotificationIntentService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
FirebaseInstanceIdService 类
public class MyFireBaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFireBaseInstanceIDService.class.getSimpleName();
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
if (refreshedToken!=null) {
SettingPreferences.setStringValueInPref(this, SettingPreferences.REG_ID, refreshedToken);
}
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}}
FirebaseMessagingService 类。
public class GCMNotificationIntentService extends FirebaseMessagingService {
// Sets an ID for the notification, so it can be updated
public GCMNotificationIntentService() {
super();
}
@Override
public void onMessageReceived(RemoteMessage message) {
}}