🔗
Expo Managed WorkflowでAndroidのDeeplinkをフォアグラウンド状態で受信できない問題の解決方法
問題
Expo Managed WorkflowでAndroidアプリにDeeplinkを設定した場合、アプリがフォアグラウンドにいるときに新しいURLを受け取っても、URLの変更を検知できないことがあります。
原因
AndroidのMainActivity
でonNewIntent
が正しく実装されていないと、インテントが更新されてもアプリ側で新しい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.json
のexpo.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
参考:
Discussion