【发布时间】:2015-01-27 06:54:33
【问题描述】:
我正在尝试使用 Dagger 将 Context 引入到一个类中,这就是我所拥有的以及随之而来的错误:
@Module(injects = { MyApp.class, TransportModule.class }, library = true, includes = { TransportModule.class })
public class AppModule {
private final MyApp remoteApp;
public AppModule(MyApp remoteApp) {
this.remoteApp = remoteApp;
}
@Provides
@Singleton
Context provideApplicationContext() {
return remoteApp;
}
}
应用程序类:
@Override
public void onCreate() {
instance = this;
super.onCreate();
objectGraph = ObjectGraph.create(getModules().toArray());
objectGraph.inject(this);
mContext = getApplicationContext();
private List<Object> getModules() {
return Arrays.<Object>asList(new AppModule(this));
}
public ObjectGraph createScopedGraph(Object... modules) {
return objectGraph.plus(modules);
}
public static Context getContext() {
return mContext;
}
public static LoQooApp getInstance() {
return instance;
}
}
DeviceInfo.java:
public class DeviceInfo {
static LoQooApp baseApp;
@Inject
static Context mContext;
public DeviceInfo() {
}
public static boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(mContext);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
Log.v(TAG, Integer.toString(resultCode));
} else {
Log.i(TAG + "NOPE", "This device is not supported.");
}
return false;
}
return true;
}
}
LogCat 错误:
Caused by: java.lang.NullPointerException: Attempt to invoke
virtual method 'android.content.pm.PackageManager
android.content.Context.getPackageManager()' on a null object reference at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvai lable(Unknown Source)
Caused by: java.lang.NullPointerException: Attempt to invoke
virtual method 'android.content.pm.PackageManager
android.content.Context.getPackageManager()' on a null object
reference
at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvai lable(Unknown Source)
DeviceInfo 中有一大堆需要上下文的方法,它们都失败了。 如何通过 Dagger 甚至不使用 Dagger 将上下文带入该类?
【问题讨论】:
-
您不想保留对
Context的静态引用。在您的方法中将其作为参数提供,或者创建一个DeviceInfo实例,该实例在其构造函数中采用Context。然后,您可以使用它将DeviceInfo实例注入到您的类中。 -
在哪里注入DeviceInfo?其他使用其方法的类,例如 BaseActivity?
标签: java android singleton dagger