React native Linking.getInitialUrl on Android called always

Viewed 1578

I've a React-Native app with the following code (here App.js, the app entry point) that manages deep link on Android.

Linking.getInitialURL().then((deepLinkUrl) => {
  if (deepLinkUrl) {
    manageDeepLink(deepLinkUrl);
  } else {
    Navigation.startSingleScreenApp('rootScreen');
  }
});

The problem here is that getInitialURL is called every time I launch my app, from both deep link or normally, and everytime it contains deepLinkUrl parameter empty. I've registered in AndroidManifest my intent as follows:

<application
    android:name=".MainApplication"
    android:allowBackup="true"
    android:launchMode="singleTask"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustResize">
        <!-- deeplink -->
        <intent-filter android:label="@string/app_name">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="myapp" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

UPDATE I'm using react-native navigation to register screens, if this can e useful.

2 Answers

It seems it doesn't work if you register listener too soon in the app lifecycle (ex. directly in some .js file, so it's executed when app is loaded).

If you move it into componentDidMount() on the root component everything works fine.

    componentDidMount() {
        Linking.addEventListener('url', event => {
            console.warn('URL', event.url)
        })

        Linking.getInitialURL().then(url => {
            console.warn('INITIAL', url)
        })
    }

Because you added android:launchMode="singleTask" to AndroidManifest.xml. Please modify it to android:launchMode="singleTop", then your problem will be gone.

Related