如何从 createPackageContext() 获取 ApplicationContext

How to get an ApplicationContext from createPackageContext()

代码如下:

Context c = getContext().createPackageContext("com.master.schedule", Context.CONTEXT_INCLUDE_CODE|Context.CONTEXT_IGNORE_SECURITY);

int id = c.getResources().getIdentifier("layout_main", "layout","com.master.schedule"); LayoutInflater inflater = LayoutInflater.from(c); piflowView = inflater.inflate(id, null);

com.master.schedule is my package project.The upside code presents how the other project(his package name is different to mine) inflate my project, in my project there are only an ViewGroup(I don’t'没有 activity);当我调用“context.getApplicationContext”时,它 return 为空...我的项目代码如下:

public class CascadeLayout extends RelativeLayout {
    private Context context;
    public CascadeLayout(Context context) {
        super(context);
        this.context=context.getApplicationContext();
    }
     @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        //here: context == null;
    }
}

我发现 createPackageContext() 给我的“Context c”是 ContextImpl 类型;我认为这是造成 return null;

那么如何获取一个不为null的ApplicationContext呢?

顺便说一句:请不要说服我不要调用getApplicationContext();因为我必须使用.jar,所以jar需要在其中调用getApplicationContext()

非常感谢。

createPackageContext() 的文档指出:

Return a new Context object for the given application name. This Context is the same as what the named application gets when it is launched, containing the same resources and class loader.

从字里行间看出,这个上下文显然应该是 "the same" 作为应用程序上下文。但是,您会看到它的 getApplicationContext() returns null,因此我们可以尝试使用 ContextWrapper 来解决这个问题(见下文)。希望这种方法足以满足您的需求。

在下面的代码中,WrappedPackageContext用于包装createPackageContext()返回的"package context",覆盖getApplicationContext()实现,使其returns本身.

class WrappedPackageContext extends ContextWrapper {
    WrappedPackageContext(Context packageContext) {
        super(packageContext);
    }

    @Override
    public Context getApplicationContext() {
        return this;
    }
}

Context createApplicationContext(Context packageContext) {
    return new WrappedPackageContext(packageContext);
}