Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

setRegistrationTokenUpdateListener does not return the deviceToken #109

Closed
seanlau555 opened this issue Aug 21, 2017 · 34 comments
Closed

setRegistrationTokenUpdateListener does not return the deviceToken #109

seanlau555 opened this issue Aug 21, 2017 · 34 comments

Comments

@seanlau555
Copy link

I am moving from react-native-push-notification to this one because of the conflict of the RNN-RNPN. However, it does not work in my case. PendingNotifications.getInitialNotification returns undefined and NotificationsAndroid.setRegistrationTokenUpdateListener does not returns deviceToken.
I can see the result and correct response in Android monitor Logging (App initialized => publishing existing token (dc5oJgMT-qw:APA ...). But, I cannot get any response from JS. What can I do with that?
I also try the example of this one.
https://github.com/chrise86/rn-notification-navigation
It gives me the same result.

@lidanh lidanh self-assigned this Aug 21, 2017
@seanlau555
Copy link
Author

seanlau555 commented Aug 24, 2017

I found a solution by removing the ReactNativeHost in MainApplication. I don't know why but it works anyway.

Then, the second question is when the device receive A and B notices (A first, then B), tapping or opening B notice will return A. The result is difficult to control using this library.

I suggest you guest can take the reference of react-native-push-notification. It makes things simpler, more directly and result oriented.

@arcollector
Copy link

did you find a solution when tappening on B notification case?

@zj-lin-golorry
Copy link

zj-lin-golorry commented Aug 27, 2017

The token did exist and the event emitter did got called the method below, but it could likely be due to context issue that the event was not received by the JS listener.

protected void sendTokenToJS() {
    final ReactInstanceManager instanceManager = ((ReactApplication) mAppContext).getReactNativeHost().getReactInstanceManager();
    final ReactContext reactContext = instanceManager.getCurrentReactContext();
    Log.d("reactContext", String.valueOf(reactContext != null && reactContext.hasActiveCatalystInstance())); // logs true
    if (reactContext != null && reactContext.hasActiveCatalystInstance()) {
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(TOKEN_RECEIVED_EVENT_NAME, sToken);
    }
}

@arcollector
Copy link

I solved this issue by calling NotificationsAndroid.refreshToken(); before NotificationsAndroid.setRegistrationTokenUpdateListener(this.onPushRegistered);

@kholiavko-roman
Copy link

Does anybody can share an example please ?
I download example by seanlau555, inserted next code to app.js:

NotificationsAndroid.refreshToken();

NotificationsAndroid.setRegistrationTokenUpdateListener(onPushRegistered);

function onPushRegistered(token) {
  console.log('token is');
  console.log(token);
}

but I didn`t see the token in console.

@thadeu
Copy link

thadeu commented Nov 3, 2017

+1

@ChildishDanbino
Copy link

ChildishDanbino commented Nov 12, 2017

Has anyone been able to find a fix for this? Without being able to grab the device token on Android this renders the library almost useless. Below is my code.

Javascript:

import PropTypes from 'prop-types';
import { Children, Component } from 'react';
import { isAndroid, isIos } from 'react-native-device-detection';
import NotificationsIOS, { NotificationsAndroid } from 'react-native-notifications';

/**
 * Notifications Provider handles all push notification functionality of the app
 * See https://github.com/wix/react-native-notifications for docs
 */
class NotificationsProvider extends Component {
  componentDidMount() {
    if (isIos) {
      NotificationsIOS.requestPermissions();
      NotificationsIOS.addEventListener('remoteNotificationsRegistered', token => console.log(`My Token ${token}`));
    } else if (isAndroid) {
      console.log('******* COMPONENT MOUNTED ******* ');
      NotificationsAndroid.refreshToken();
      NotificationsAndroid.setRegistrationTokenUpdateListener((deviceToken) => {
        console.log(`Push-notifications registered! ${deviceToken}`);
      });

      // On Android, we allow for only one (global) listener per each event type.
      NotificationsAndroid.setNotificationReceivedListener((notification) => {
        console.log(`Notification received on device ${notification.getData()}`);
      });

      NotificationsAndroid.setNotificationOpenedListener((notification) => {
        console.log(`Notification opened by device user ${notification.getData()}`);
      });
    }
  }

  componentWillUnmount() {
    if (isIos) {
      NotificationsIOS.removeEventListener('remoteNotificationsRegistered');
    }
  }

  render() {
    return Children.only(this.props.children);
  }
}

NotificationsProvider.propTypes = {
  children: PropTypes.object.isRequired
};

export default NotificationsProvider;

Main Application.java (ExpoKit)


import android.support.multidex.MultiDexApplication;


import com.facebook.react.ReactPackage;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;

import com.wix.reactnativenotifications.RNNotificationsPackage;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends MultiDexApplication implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
              //new MainReactPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  public List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
            // Add your own packages here!
            // TODO: add cool native modules

            // Needed for `react-native link`
            // new MainReactPackage()
            new RNNotificationsPackage(MainApplication.this)
    );
  }

}```

@arcollector
Copy link

dont use RNN as if it was a Component thing
initialize it before React Native start (AppRegistry.registerComponent)

@ChildishDanbino
Copy link

@arcollector even so. Wouldn't calling NotificationsAndroid.refreshToken(); cause the token to be refreshed and thus setRegistrationTokenUpdateListener would be fired?

@arcollector
Copy link

it doesnt matter, token will always be the same, token only changes when app is unistalled and isntalled again

@ChildishDanbino
Copy link

I understand. The issue is that the following code is never being hit no matter where in the app it is placed. I am only able to receive the token by looking through the Android Studio Logs

      NotificationsAndroid.setRegistrationTokenUpdateListener((deviceToken) => {
        console.log(`Push-notifications registered! ${deviceToken}`);
      });

@lucadegasperi
Copy link

Same here, that code is never hit.

@ChildishDanbino
Copy link

ChildishDanbino commented Nov 16, 2017

Looks like it’s an issue for sure. I’ll see if we can pinpoint the problem and open a PR. We are experiencing this issue on a detached ExpoKit app. Are people experiencing the same issue on regular react-native?

@ChildishDanbino
Copy link

ChildishDanbino commented Nov 17, 2017

@lucadegasperi @thadeu I solved it! By writing native code.... despite I have never written Java in my life lol.

In the GcmToken.js file located in the com.wix.reactnativenotifications directory do the following steps.

import the following

import com.wix.reactnativenotifications.core.AppLifecycleFacade;
import com.wix.reactnativenotifications.core.AppLifecycleFacadeHolder;

and the following line below "final protected Context mAppContext;"

final protected AppLifecycleFacade mAppLifecycleFacade = AppLifecycleFacadeHolder.get();

it should look like this

public class GcmToken implements IGcmToken {

    final protected Context mAppContext;
    final protected AppLifecycleFacade mAppLifecycleFacade = AppLifecycleFacadeHolder.get();

    protected static String sToken;

Then overwrite the sendTokenToJs() method as follows:

 protected void sendTokenToJS() {
        final ReactContext reactContext = mAppLifecycleFacade.getRunningReactContext();

        // Note: Cannot assume react-context exists cause this is an async dispatched service.
        if (reactContext != null && reactContext.hasActiveCatalystInstance()) {
            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(TOKEN_RECEIVED_EVENT_NAME, sToken);
        }

Enjoy your push notification token sent to the Javascript! Please let me know if this works for you guys as I am willing to open a PR to ensure no one has to go through this again.

@lidanh: Is Wix actively supporting this package? Would you like me to open a PR with the code above to get this bug closed?

@thadeu
Copy link

thadeu commented Nov 17, 2017

@Daadler6 I'll test, I'll give you a feedback as soon as possible.

Thanks.

@ChildishDanbino
Copy link

One thing to note as well. I refresh the token... this might not be necessary depending on where you have the listener in your application.

    NotificationsAndroid.refreshToken();
      NotificationsAndroid.setRegistrationTokenUpdateListener((deviceToken) => {
        console.log(`Push-notifications registered! ${deviceToken}`);
      });

@jameshedaweng
Copy link

Is anyone looking at this issue?
I see the same problem here, and haven't been able to get a solution either. One interesting phenomenon that I see is, initially the token is never sent to the JS part. But if the Android app crashed for whatever reason, the token appears.

charles001636 added a commit to charles001636/react-native-notifications that referenced this issue May 3, 2018
according to the recommendations in wix#109
@charles001636
Copy link

@Daadler6 Thanks! it works for me.
I forked it to prevent overwrite while running npm/yarn.

@rickycpadilla
Copy link

After setting up the Google Play store in my emulator and adding
NotificationsAndroid.refreshToken();
I was finally able to log my device token.

@ronilitman
Copy link

@Daadler6 Unfortunately this does not work for me, any other suggestions?

@ChildishDanbino
Copy link

@ronilitman - ended up using https://github.com/zo0r/react-native-push-notification. Much much easier to work with on IOS and Android (especially if you are using Expo)

@youssefatti
Copy link

@ronilitman Could you check in your android/gradles.properties if android.enableAapt2=false

@ronilitman
Copy link

@youssefatti Looks like this is working. thank you!

@ronilitman
Copy link

ronilitman commented Sep 13, 2018

@youssefatti As I see Aapt1 is going to be deprecated until the end of 2018, so is it ok to use it still? what are the alternatives?

@youssefatti
Copy link

@ronilitman yes you can use it for now. i will looking for remove it later. Alternatives !! no clue for now

@gamsim
Copy link

gamsim commented Dec 20, 2018

For me it was android.enableAapt2=false in android/gradles.properties

@dbelchev
Copy link

dbelchev commented Jan 8, 2019

@youssefatti Have you figured this out? :)

This will become a serious issue with some of the following Gradle upgrades! I don't know who maintain the package to make a mention in the comment.

@youssefatti
Copy link

@dbelchev not yet, and im afraid to going througth this issue. and i will need to update my app very soon. i will keep you in touch if any changes

@MattHaugen
Copy link

In case this helps others, I was experiencing a very similar issue recently where setRegistrationTokenUpdateListener was never being called and thus our app never received a new token. Setting android.enableAapt2=false did fix the problem but caused other build issues so I had to dig deeper.

The installation docs recommend that the GCM Sender ID be defined similar to this

<manifest>
...
	<application>
	...
		// Replace '1234567890' with your sender ID.
		// IMPORTANT: Leave the trailing \0 intact!!!
	    <meta-data android:name="com.wix.reactnativenotifications.gcmSenderId" android:value="1234567890\0"/>
	</application>
</manifest>

As I understand it the \0 is a technique to ensure the variable is cast as a string, but what I observed is that after we upgraded our app to React Natve .57 (and all of the Android/Gradle/etc stuff that went with it), that 0 was actually being appended to the end of the ID.

This was resulting in a INVALID_SENDER error from Google's GCM library. This was swallowed by the React Native Notifications code, and the end result was no token being sent to setRegistrationTokenUpdateListener.

The fix for us was to define a variable in a strings.xml file like <string name="gcm_sender_id">55555555555</string> and then in the AndroidManifest.xml files do something like

<meta-data
        android:name="com.wix.reactnativenotifications.gcmSenderId"
        android:value="@string/gcm_sender_id"
      />

My guess is that android.enableAapt2=false uses the old compiler, which interprets that string casting different than than the new method.

Sorry for the length of this, but hoping this saves some other folks some pain. If I'm not the only one experiencing this, we should also get the install docs updated for the library.

@msantang78
Copy link

Awesome @MattHaugen that solved it!
Thanks!

@youssefatti
Copy link

@MattHaugen thanks it works

@lxcid
Copy link

lxcid commented Apr 2, 2019

@MattHaugen excellent debugging and information! Many thanks!

@stale
Copy link

stale bot commented Jul 24, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
If you believe the issue is still relevant, please test on the latest Detox and report back. Thank you for your contributions.

@stale stale bot added the 🏚 stale label Jul 24, 2019
@stale
Copy link

stale bot commented Jul 31, 2019

The issue has been closed for inactivity.

@stale stale bot closed this as completed Jul 31, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Development

No branches or pull requests