2015-12-14 17 views
1

是否可以使用Dagger2注入基於SDK版本的具體實現?Dagger2:可以根據Android版本注入嗎?

例如

// MediaPlayerComponent.class 
@Component(modules = {MediaPlayerModule.class} 
public interface MediaPlayerComponent 
{ 
    void inject(MediaPlayerUI ui) 
} 

// MediaPlayerUI.java 
public class MediaPlayerUI 
{ 
    @Inject 
    public MediaPlayer mPlayer; 
} 

// GingerbreadMediaPlayer.java 
public class GingerbreadMediaPlayer extends MediaPlayer {...} 

// IceCreamSandwichMediaPlayer.java 
public class IceCreamSandwichMediaPlayer extends MediaPlayer {...} 

回答

3

是的,就決定哪兩種實現的應MediaPlayerModule模塊與@Provides,返回一個通用MediaPlayer的一個註解的具體方法返回。

0

理論上這是可能的,我沒有這麼做過,因爲我沒有必要,但我認爲以下情形將工作:

  • 你應該有一個定義的需求,一個父ApplicationComponent你的應用。我們稱之爲ApplicationComponent。
  • 現在讓我們假設您想要爲API21和更高版本以及API 21以下創建兩個不同的依賴關係。您應該創建兩個從您的應用程序組件繼承的組件,我們將它們稱爲Application21Component和ApplicationBelow21Component。
  • 對於兩個組成部分,你應該有一個不同的ApplicationModule,告訴你的應用程序組件如何獲得依賴性所需
  • 在你的應用程序類「getComponent」功能的人體會出現類似以下

    東西

    public ApplicationComponent getComponent(){ if (mApplicationComponent == null) { if (Build.VERSION.SDK_INT >= 21) { mApplicationComponent = DaggerApplication21Component.builder() .applicationModule(new ApplicationModule(this)) .build(); } else { mApplicationComponent = DaggerApplicationBelow21Component.builder() .applicationModule(new ApplicationModule(this)) .build(); } } return mApplicationComponent; }