Reputation: 799
I'd like to open a React Native Android deeplink when the app is open in the background. Here's how I handle other similar cases:
iOS App is open in the background:
Linking.addEventListener('url', this.handleOpenURL);
iOS app is closed in the background
Linking.getInitialURL().then(url => this.handleOpenURL({ url }));
Android app is open in the background: ? - What's the best way to handle this case?
Android app is closed in the background:
Linking.getInitialURL().then(url => this.handleOpenURL({ url }));
Upvotes: 6
Views: 4884
Reputation: 1008
Add this to MainActivity.java
@Override
public void onNewIntent(Intent intent) {
if(intent.getData() != null) {
Uri deepLinkURL = intent.getData();
ReactContext reactContext = getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
sendEvent(reactContext,"deepLinking", deepLinkURL.toString());
}
}
private void sendEvent(ReactContext reactContext,
String eventName,
String str) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, str);
}
then add this to react
componentDidMount() {
this.subscription = DeviceEventEmitter.addListener('deepLinking', function(e: Event) {
// handle event
});
}
componentWillUnmount() {
// When you want to stop listening to new events, simply call .remove() on the subscription
this.subscription.remove();
}
Upvotes: 4
Reputation: 1310
The react native Linking does not seem to work with android running in the background. You can solve this by using native android code. In the main activity override the method like this:
@Override
public void onNewIntent(Intent intent) {
if(intent.getData() != null) {
Uri deepLinkURL = intent.getData();
DeepLink deepLink = new DeepLink(deepLinkURL.toString());
}
}
What you need to do then is integrate this java code with the react native javascript. This can be done with react native - native modules. There is some documentation on it on the website. To make it a more effective solution you can use something like http://square.github.io/otto/ to create an event bus that listens on that deeplink object. Then the deeplink event will fire effectively once a event has occured. I hope this helps man :)
Upvotes: 4