应用程序上下文使用Dagger?

时间:2015-01-27 06:54:33

标签: java android singleton dagger

我试图使用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将上下文带入该类?

1 个答案:

答案 0 :(得分:1)

可以进行静态注射(How to inject into static classes using Dagger?),但这应该是例外。你应该把方法和字段都不是静态的。

因此,DeviceInfo看起来像

@Inject public DeviceInfo(Context context) {
    mContext = context;
}
public boolean checkPlayServices() { //not static

然后,注入DeviceInfo

public class MyApp {
    @Inject DeviceInfo deviceInfo;

由objectGraph.inject(this)设置;在onCreate。

如果您需要在活动中使用DeviceInfo,您还可以在onCreate

中调用inject
MyApp app = (MyApp) getApplication();
app.getObjectGraph().inject(this);

您还需要将活动添加到AppModule的injects部分。