RoboGuice custom module application context

2019-07-19 06:31发布

问题:

How do I get the application context in my custom module? Here is the code for my module:

public class MyModule extends AbstractModule {
    @Override
    @SuppressWarnings("unchecked")
    protected void configure() {
        // Package Info
        try {
            final PackageInfo info = application.getPackageManager().getPackageInfo(
                    application.getPackageName(), PackageManager.GET_META_DATA);
            bind(PackageInfo.class).toInstance(info);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

I am trying to get the metadata for the application. The default module version of PackageInfo doesn't have meta data, hence I need custom binding.

回答1:

Just inject it in constructor

public final class MyModule extends AbstractModule
{
    private final Context   context;

    @Inject
    public MyModule(final Context context)
    {
        super();
        this.context = context;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void configure() {
        // Package Info
        try {
            final PackageInfo info = context.getPackageManager().getPackageInfo(
                context.getPackageName(), PackageManager.GET_META_DATA);
            bind(PackageInfo.class).toInstance(info);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}