Dagger和ButterKnife - 我可以注入Android AudioManager实例

时间:2014-12-21 18:18:56

标签: android dependency-injection dagger butterknife

如何注入AudioManager实例?我需要一个上下文,我没有一个?

这是我的班级使用Dagger注射:

public abstract class ListPageActivity extends BaseActivity {

private SoundPool mSoundPool;
private int mSoundID;
boolean plays = false, loaded = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//ButterKnife.inject(this);
}


public void loadBrandSound(){
mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

    @Override
    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
        loaded = true;
    }
});
mSoundID = mSoundPool.load(this, R.raw.ducksound, 1);

}

@Inject AudioManager am; //i want to inject this
public void playBrandSound() {



     /*AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); commented out as i want to
inject it*/
    int volume_level= am.getStreamVolume(AudioManager.STREAM_MUSIC);

    // Is the sound loaded already ?
    if (loaded && !plays) {
        mSoundPool.play(mSoundID, volume_level, volume_level, 1, 0, 1f);
        plays = true;

    }
}

public void stopBrandSound() {

    if (mSoundPool != null && plays) {
        mSoundPool.stop(mSoundID);
        mSoundPool.release();
        plays = false;
    }

}

}

这是我失败的名为ActivityModule.java的模块,我想声明一个可以注入我的ListPageActivity的audioManager实例:

@Module(
        library = true,
        injects= {
                ListPageActivity.class,
                MainActivity.class
        }
) public class ActivityModule {

    @Provides
    AudioManager provideAudioManager(){return (AudioManager) getSystemService(AUDIO_SERVICE);
//the above fails to compile as i need a context, how can i get one ?
}
}

我的匕首模块已经正常工作,所以我设置正确。还有一种更简单的方法来注入系统服务,因为这样常见而不是这种方式? ButterKnife我想的可能有些东西我可以简单地注入一个systemService,就像我可以注入一个视图一样。

1 个答案:

答案 0 :(得分:1)

假设BaseActivity为您处理Activity注入,您应该能够:

将上下文作为参数传递给“provideAudioManager”方法,然后使用provideContext()方法从活动或应用程序中提供上下文。

像这样的东西

private Activity mActivity;

public ActivityModule(Activity activity){
    mActivity = activity;
}

Context provideContext(){
    return mActivity;
}

AudioManager provideAudioManager(Context context){
   return (AudioManager) context.getSystemService(AUDIO_SERVICE);
}