如何在非活动类locationmanager(AudioManager)中使用getsystemservice

时间:2013-06-14 13:06:36

标签: android

我无法将主要活动OnCreate方法中的任务卸载到另一个类来完成繁重的工作。

当我尝试从非Activity类调用getSystemService时会抛出异常。

非常感谢任何帮助:)

public void playSound() {
    SoundPool soundPool;
    int soundID;
    final boolean loaded = false;

    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                int status) {
            loaded = true;
        }
    });
    soundID = soundPool.load(getContext(), R.raw.voice, 1);
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    float actualVolume = (float) audioManager
            .getStreamVolume(AudioManager.STREAM_MUSIC);
    float maxVolume = (float) audioManager
            .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    float volume = actualVolume / maxVolume;
    // Is the sound loaded already?
    if (loaded) {
        soundPool.play(soundID, volume, volume, 1, 0, 1f);
        Log.e("Test", "Played sound");
    }
}

1 个答案:

答案 0 :(得分:1)

尝试以下方法,

    public void playSound() {
SoundPool soundPool;
int soundID;
final boolean loaded = false;

soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
    public void onLoadComplete(SoundPool soundPool, int sampleId,
            int status) {
        loaded = true;
    }
});
soundID = soundPool.load(getContext(), R.raw.voice, 1);
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
float actualVolume = (float) audioManager
        .getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
        .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded) {
    soundPool.play(soundID, volume, volume, 1, 0, 1f);
    Log.e("Test", "Played sound");
}

}