2

如何在我的自定义模块中获取应用程序上下文?这是我的模块的代码:

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

我正在尝试获取应用程序的元数据。PackageInfo 的默认模块版本没有元数据,因此我需要自定义绑定。

4

1 回答 1

3

只需将其注入构造函数

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

}

于 2013-03-26T14:00:17.400 回答