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

如何获取代表Fragment Bundle的Bundle对象?当前方法返回宿主Bundle

获取Fragment Bundle的正确方法

在OSGi架构中,Fragment Bundle没有独立的类加载器,其类资源由宿主Bundle的类加载器加载,因此直接调用FrameworkUtil.getBundle(getClass())会返回宿主Bundle实例。要获取Fragment自身的Bundle对象,可采用以下两种可靠方式:

  • 通过BundleContext遍历筛选
    如果能获取到Fragment的BundleContext(通常在Fragment的Activator启动方法中传入),可以遍历系统中已安装的所有Bundle,通过Symbolic Name唯一标识定位Fragment Bundle:

    BundleContext fragmentContext = ...; // 来自Fragment Activator的BundleContext
    Bundle targetFragment = null;
    for (Bundle bundle : fragmentContext.getBundles()) {
        // 替换为你的Fragment Bundle的Symbolic Name
        if("com.example.your.fragment".equals(bundle.getSymbolicName())) {
            targetFragment = bundle;
            break;
        }
    }
    
  • 利用Fragment Activator直接获取
    为Fragment实现自定义BundleActivator时,启动方法传入的BundleContext属于Fragment自身,通过该上下文可直接拿到Fragment Bundle:

    public class MyFragmentActivator implements BundleActivator {
        @Override
        public void start(BundleContext context) throws Exception {
            Bundle fragmentBundle = context.getBundle();
            // 此处获取的即为Fragment自身的Bundle对象
        }
    
        @Override
        public void stop(BundleContext context) throws Exception {
            // 资源清理逻辑
        }
    }
    

注意:Fragment Bundle依赖宿主Bundle的生命周期,只有当宿主Bundle处于ACTIVE状态时,Fragment才能正常发挥作用,此时其Bundle对象通常处于RESOLVED或ACTIVE状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:01:46