2015-01-27 6 views
0
나는 단검을 사용하여 클래스의 문맥을 끌어하기 위해 노력하고있어

, 여기에 내가 무엇을 그리고 찾다 오류 :응용 프로그램 컨텍스트 단검 사용?

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

} 

로그 캣 오류 :

DeviceInfo에는 컨텍스트가 모두 필요한 메서드가 많이 있습니다. 모두 실패합니다. 대거를 통해 또는 단검없이 컨텍스트를 가져 오는 방법은 무엇입니까?

+0

정적 참조를 '컨텍스트'에 보관하고 싶지는 않습니다. 메소드의 매개 변수로 제공하거나 생성자에서'Context'를 취하는'DeviceInfo' 인스턴스를 생성하십시오. 그런 다음 그것을 사용하여 클래스에'DeviceInfo' 인스턴스를 삽입 할 수 있습니다. – nhaarman

+0

DeviceInfo를 어디에 삽입합니까? BaseActivity와 같은 메소드를 사용하는 다른 클래스는 무엇입니까? – sirvon

답변

1

정적 주입 (How to inject into static classes using Dagger?)을 수행 할 수 있지만 예외입니다. 메서드와 필드를 정적이 아닌 오히려 만들어야합니다.

그래서 DeviceInfo 그럼

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

같은 DeviceInfo objectGraph.inject가 (이)에 의해 설정된다

public class MyApp { 
    @Inject DeviceInfo deviceInfo; 

를 주입 보인다; inCreate에서. 당신이하는 행동이에 DeviceInfo 필요한 경우

, 당신은 또한 당신은 또한 AppModule의를 분사 부분에 활동을 추가 할 필요가에서 onCreate

MyApp app = (MyApp) getApplication(); 
app.getObjectGraph().inject(this); 

을에 주입 호출합니다.

+0

Dagger/DI가 이미 나에게 미로이기 때문에 어떤 예제 코드를 제공 할 수 있습니까? 당신이 묘사하고있는 것을 "볼"필요가 있습니다. 타이 – sirvon

관련 문제