const { withMainActivity } = require('@expo/config-plugins'); /** * 在 MainActivity 中添加 onConfigurationChanged 方法 * 用于监听系统深色模式变化并通知 React Native */ const withMainActivityConfigChange = (config) => { return withMainActivity(config, async (config) => { const { contents } = config.modResults; // 检查是否已经添加了 onConfigurationChanged if (contents.includes('onConfigurationChanged')) { return config; } // 需要添加的 imports const importsToAdd = `import android.content.Intent import android.content.res.Configuration`; // 需要添加的方法 const methodToAdd = ` /** * 监听系统配置变化(包括深色模式切换),并广播给 React Native * 这对于 Appearance API 正确检测系统主题至关重要 */ override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) val intent = Intent("onConfigurationChanged") intent.putExtra("newConfig", newConfig) sendBroadcast(intent) } `; let newContents = contents; // 添加 imports(在已有 imports 后面) if (!newContents.includes('import android.content.Intent')) { // 找到最后一个 import 语句 const importRegex = /import [^\n]+\n/g; const imports = newContents.match(importRegex); if (imports && imports.length > 0) { const lastImport = imports[imports.length - 1]; const lastImportIndex = newContents.lastIndexOf(lastImport); const insertPosition = lastImportIndex + lastImport.length; newContents = newContents.slice(0, insertPosition) + importsToAdd + '\n' + newContents.slice(insertPosition); } } // 在类体的开头添加 onConfigurationChanged 方法 // 找到类定义后的第一个方法或属性 const classBodyRegex = /class MainActivity\s*:\s*ReactActivity\s*\(\)\s*\{([\s\S]*)/; const match = newContents.match(classBodyRegex); if (match) { // 找到 onCreate 方法之前插入 const onCreateIndex = newContents.indexOf('override fun onCreate'); if (onCreateIndex !== -1) { newContents = newContents.slice(0, onCreateIndex) + methodToAdd + newContents.slice(onCreateIndex); } } config.modResults.contents = newContents; return config; }); }; module.exports = withMainActivityConfigChange;