question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unregistered token - Android

See original GitHub issue

I have simple problem with token on Android. Firebase tells me that token is unregistered. On iOS everything works fine.

here is my code:

componentDidMount() {
        console.log('FCMEVENT', FCMEvent);
        if(this.props.isAuthenticated && !this.state.notificationRegistered) {
            this.registerNotification();
        }
    }

    componentWillReceiveProps(newProps) {
        if(newProps.isAuthenticated && !this.state.notificationRegistered) {
            this.registerNotification();
        } else {
            this.removeNotification();
        }
    }

    getToken = () => AsyncStorage.getItem(TOKEN)
        .then((data) => {
            return data;
        })
        .catch(() => {});

    registerNotification = async () => {
        const token = await this.getToken();
        this.handleRegister();
        console.log(token);
        this.setState({
            notificationRegistered: true,
        });
    };

    removeNotification = () => {
        FCM.on(FCMEvent.Notification, notif => {
            AsyncStorage.setItem('lastNotification', JSON.stringify(notif));
            if (notif.opened_from_tray) {
                setTimeout(() => {
                    if(notif._actionIdentifier === 'reply') {
                        if (AppState.currentState !== 'background') {
                            console.log(`User replied ${JSON.stringify(notif._userText)}`);
                            alert(`User replied ${JSON.stringify(notif._userText)}`);
                        } else {
                            AsyncStorage.setItem('lastMessage', JSON.stringify(notif._userText));
                        }
                    }
                    if(notif._actionIdentifier === 'view') {
                        alert('User clicked View in App');
                    }
                    if(notif._actionIdentifier === 'dismiss') {
                        alert('User clicked Dismiss');
                    }
                }, 1000);
            }
        });
        this.setState({ notificationRegistered: false });
    };

    handleRegister = async () => {
        await FCM.requestPermissions({ badge: false, sound: true, alert: true });
        FCM.getFCMToken().then((token) => {
            this.props.setDeviceForNotification({
                deviceId: Constants.deviceId,
                pushToken: token,
                deviceType: Platform.OS,
            });
        });
AsyncStorage.getItem('lastNotification').then((data) => {
            if(data) {
                // if notification arrives when app is killed, it should still be logged here
                console.log('last notification', JSON.parse(data));
                AsyncStorage.removeItem('lastNotification');
            }
        });

        AsyncStorage.getItem('lastMessage').then((data) => {
            if(data) {
                // if notification arrives when app is killed, it should still be logged here
                console.log('last message', JSON.parse(data));
                AsyncStorage.removeItem('lastMessage');
            }
        });

        const showLocalNotification = () => {
            FCM.presentLocalNotification({
                id: new Date().valueOf().toString(),         // (optional for instant notification)
                title: "Test Notification with action",      // as FCM payload
                body: "Force touch to reply",                // as FCM payload (required)
                show_in_foreground: true                     // notification when app is in foreground (local & remote)
            });
        };

        FCM.on(FCMEvent.Notification, notif => {
            console.log('NotificationMESSAGE', notif);

            if (Platform.OS === 'ios' && notif._notificationType === NotificationType.WillPresent && !notif.local_notification) {
                // this notification is only to decide if you want to show the notification when user if in forground.
                // usually you can ignore it. just decide to show or not.
                notif.finish(WillPresentNotificationResult.All);
                return;
            }

            if (notif.opened_from_tray) {
                setTimeout(() => {
                    alert(`User tapped notification\n${JSON.stringify(notif)}`);
                }, 500);
            }

            if (Platform.OS === 'ios') {
                /*
                    optional
                    iOS requires developers to call completionHandler to end notification process.
                    If you do not call it your background remote notifications could be throttled, to read more about it see the above documentation link.
                    This library handles it for you automatically with default behavior
                    (for remote notification, finish with NoData; for WillPresent, finish depend on "show_in_foreground").
                    However if you want to return different result, follow the following code to override notif._notificationType is available for iOS platfrom
                */
                switch (notif._notificationType) {
                    case NotificationType.Remote:
                        notif.finish(RemoteNotificationResult.NewData); // other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed
                        break;
                    case NotificationType.NotificationResponse:
                        notif.finish();
                        break;
                    case NotificationType.WillPresent:
                        notif.finish(WillPresentNotificationResult.All); // other types available: WillPresentNotificationResult.None
                        // this type of notificaiton will be called only when you are in foreground.
                        // if it is a remote notification, don't do any app logic here. Another notification callback will be triggered with type NotificationType.Remote
                        break;
                    default:
                        break;
                }
            }
        });

        FCM.on(FCMEvent.RefreshToken, token => {
            console.log('TOKEN (refreshUnsubscribe)', token);
        });

        FCM.on(FCMEvent.DirectChannelConnectionChanged, (data) => {
            console.log(`direct channel connected ${data}`);
        });

        FCM.enableDirectChannel();

        setTimeout(() => {
            FCM.isDirectChannelEstablished().then((d) => {
                console.log('established', d);
            });
        }, 1000);
    };

Everything was made according to the repo example. Anyone knows what I am doing wrong?

Thanks!

React Native 0.53 React Native FCM 14.1.3 google services 10.0.1

Issue Analytics

  • State:open
  • Created 5 years ago
  • Comments:13 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
kholiavko-romancommented, Apr 17, 2018

@evollu, does token have some validity period ? Now I see the situation that I have many users that has "NotRegistered" token, but it login a few week ago and more. And I don’t understand where is the problem.

0reactions
gitsadcommented, Mar 28, 2018

Ok, I have managed this by reverting my project and ejecting to plain react native without expo. Now, my token is registered but it cost me a lot of time. For anyone whose project is with expo, I recommend to handle notifications by expo. 👍

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unregistered token error after sending one notification
I am facing this dramatic problem with my android app while using Firebase. 1. My app receives token on the first launch 2....
Read more >
Best practices for FCM registration token management
Retrieve and store registration tokens; Detect invalid token responses from the ... as token(completion): for Apple platforms or getToken() for Android) and ...
Read more >
Amazon Pinpoint for push notifications on Android ...
Unregistered or expired token. I was implementing push notification into the Activity Filter Android app, and noticed that they were not working ...
Read more >
Token unregistered - Android · Issue #25 - GitHub
I'm having an issue with my Android App. When I deploy the app to the device, All seems work perfectly, the App refresh...
Read more >
FCM token is not registered. - Support : GameSparks
Push notifications don't work because the FCM token (taken from the GS database) is not registered in Firebase's portal. They do work for...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found