0

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

4

1 回答 1

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);
}
于 2014-12-21T18:25:42.070 回答