简体   繁体   中英

How to get an ApplicationContext from createPackageContext()

The code is followed:

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 is only a ViewGroup(I don't have an activity); and when I invoke " context.getApplicationContext ", it returns null... my project code is below:

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;
    }
}

I find the createPackageContext() give the " Context c " to me is a ContextImpl type; I think that's caused return null;

So how can I get an ApplicationContext which not null?

BTW:please don't persuade me don't invoke getApplicationContext(); As I must use an .jar, the jar need to invoke getApplicationContext() in it;

thanks very very much.

The documentation for createPackageContext() states:

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.

Reading a bit between the lines, this context is apparently supposed to be "the same" as an application context. However, you are seeing that its getApplicationContext() returns null , so we can attempt to fix that by using a ContextWrapper (see below). Hopefully, this approach will be good enough for your needs.

In the following code, WrappedPackageContext is used to wrap the "package context" returned by createPackageContext() , overriding the getApplicationContext() implementation so that it returns itself.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM