如何注入 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,就像我可以注入一个视图一样。