🔗

Expo Managed WorkflowでAndroidのDeeplinkをフォアグラウンド状態で受信できない問題の解決方法

に公開

問題

Expo Managed WorkflowでAndroidアプリにDeeplinkを設定した場合、アプリがフォアグラウンドにいるときに新しいURLを受け取っても、URLの変更を検知できないことがあります。

原因

AndroidのMainActivityonNewIntentが正しく実装されていないと、インテントが更新されてもアプリ側で新しいURLを受け取れません。

解決策

setIntentを呼び出すようにMainActivity.ktを書き換える必要があります。Expo Managed Workflowでは、独自のconfig pluginを作成して自動で書き換えるのが便利です。

1. config pluginの作成例

plugins/on-new-intent-plugin.jsとして以下の内容で作成します。
com.example.app部分は、アプリのパッケージ名に変更してください。)

const { withMainActivity } = require('@expo/config-plugins');

/** @type {import('@expo/config-plugins').ConfigPlugin} */
const withOnNewIntent = (config) => {
  return withMainActivity(config, (modConfig) => {
    const mainActivity = modConfig.modResults;
    const method = `
  override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    setIntent(intent)
  }
`;

    if (!mainActivity.contents.includes('import android.content.Intent')) {
      mainActivity.contents = mainActivity.contents.replace(
        'package com.example.app',
        `package com.example.app\nimport android.content.Intent`
      );
    }

    if (!mainActivity.contents.includes('onNewIntent')) {
      mainActivity.contents = mainActivity.contents.replace(
        /class MainActivity[\s\S]*?{/,
        (match) => `${match}${method}`
      );
    }

    return modConfig;
  });
};

module.exports = withOnNewIntent;

2. app.jsonへのplugin追加例

app.jsonexpo.pluginsに以下を追加します(他の設定は省略)。

{
  "expo": {
    // ...
    "plugins": [
      // ...
      "./plugins/on-new-intent-plugin.js"
    ]
  }
}

3. prebuildしてMainActivity.ktを確認

config pluginを追加したら、以下のコマンドでprebuildを実行します。

npx expo prebuild --clean

prebuild後、android/app/src/main/java/(パッケージ名)/MainActivity.kt を開き、onNewIntentメソッドが追加されていることを確認してください。

備考

  • expo: 53.0.9
  • react-native: 0.79.2

参考:
https://github.com/react-navigation/react-navigation/issues/9154#issuecomment-980095780
https://dev.appsflyer.com/hc/docs/rn_deeplinkintegrate#android-deeplink-setup
https://www.satoslabo.com/blog/expo-android-deeplink-detection

GitHubで編集を提案

Discussion