You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android项目模块化循环依赖问题求助:跨模块打开Activity受阻

解决UnityLibrary模块打开App模块Activity的循环依赖问题

方案1:用隐式Intent启动Activity

这是最直接的解耦方式,不需要让UnityLibrary依赖App模块:

  • 在App模块的目标Activity对应的AndroidManifest.xml里配置intent-filter:
    <activity android:name=".YourTargetActivity">
        <intent-filter>
            <action android:name="com.yourapp.action.OPEN_TARGET_ACTIVITY" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    
  • 在UnityLibrary模块里通过隐式Intent启动:
    Intent intent = new Intent("com.yourapp.action.OPEN_TARGET_ACTIVITY");
    // 指定当前包名,避免匹配到其他应用的同action Activity
    intent.setPackage(getContext().getPackageName());
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    getContext().startActivity(intent);
    

方案2:基于依赖倒置的接口回调

利用两个模块都依赖的bluetooth模块做中间层,通过抽象接口解耦:

  • 在bluetooth模块定义启动Activity的接口:
    public interface ActivityLauncher {
        void launchTargetActivity(Context context);
    }
    
  • 在App模块实现这个接口:
    public class AppActivityLauncher implements ActivityLauncher {
        @Override
        public void launchTargetActivity(Context context) {
            Intent intent = new Intent(context, YourTargetActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }
    
  • 在App模块初始化时,把实现类注入到UnityLibrary:
    // 可以放在App的Application类或者启动页里
    UnityLaunchHelper.setActivityLauncher(new AppActivityLauncher());
    
  • 在UnityLibrary模块写个辅助类:
    public class UnityLaunchHelper {
        private static ActivityLauncher sLauncher;
    
        public static void setActivityLauncher(ActivityLauncher launcher) {
            sLauncher = launcher;
        }
    
        public static void launchTarget(Context context) {
            if (sLauncher != null) {
                sLauncher.launchTargetActivity(context);
            }
        }
    }
    
  • 之后在UnityLibrary里直接调用UnityLaunchHelper.launchTarget(context)就能启动目标Activity。

方案3:反射启动Activity

如果不想加额外接口,反射也是一种可选方式:

try {
    // 替换成你App模块目标Activity的全类名
    Class<?> targetActivity = Class.forName("com.yourapp.YourTargetActivity");
    Intent intent = new Intent(getContext(), targetActivity);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    getContext().startActivity(intent);
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

注意:要确保ProGuard混淆时保留这个Activity的类名,不然会出现找不到类的问题。

内容的提问来源于stack exchange,提问作者LastMomentCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 06:53:12