如何在自定义模块中获取应用程序上下文?这是我的模块的代码:
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的默认模块版本没有元数据,因此我需要自定义绑定。
答案 0 :(得分: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);
}
}
}