【问题标题】:The method load(Context, int, int) in the type SoundPool is not applicable, The method getSystemService(String) is undefinedSoundPool 类型中的 load(Context, int, int) 方法不适用,getSystemService(String) 方法未定义
【发布时间】:2011-08-16 21:59:15
【问题描述】:

注意:我是个菜鸟,所以真的不知道这些错误是什么意思。

这是我的课程代码:

package ryan.test;

import java.util.HashMap;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class MySingleton {

    private MySingleton instance;

    private static SoundPool mSoundPool;
    private HashMap<Integer, Integer> soundPoolMap;

    public static final int A1 = 1;

    private MySingleton() {
        mSoundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);// Just an example
        soundPoolMap = new HashMap<Integer, Integer>();
        soundPoolMap.put(A1, mSoundPool.load(this, R.raw.a,    1));
   //   soundPoolMap.put(A5, mSoundPool.load(MyApp.this,       R.raw.a,    1));
    }

    public synchronized MySingleton getInstance() {
        if(instance == null) {
            instance = new MySingleton();
        }
        return instance;
    }

    public void playSound(int sound) {
        AudioManager mgr = (AudioManager)MySingleton.getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);    
        float volume = streamVolumeCurrent / streamVolumeMax;

        mSoundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, 1f);     
    }

    public SoundPool getSoundPool() {
        return mSoundPool;
   }
}

我收到两个错误,第一个错误在这里:

soundPoolMap.put(A1, mSoundPool.load(this, R.raw.a,    1));

错误显示The method load(Context, int, int) in the type SoundPool is not applicable for the arguments (MySingleton, int, int) 第二个错误在这里:

AudioManager mgr = (AudioManager)MySingleton.getSystemService(Context.AUDIO_SERVICE);

错误显示The method getSystemService(String) is undefined for the type MySingleton

【问题讨论】:

    标签: android error-handling soundpool


    【解决方案1】:

    你不能在非活动类中访问系统服务,除非你传入 applicationContext 或活动。您需要在 extends Activity 类中执行此代码。

    您需要在构造函数中包含上下文才能访问声音提供者提供的服务,或者传入声音提供者管理对象才能访问这些对象。

    代码应该很简单,只需在类中声明一个 SoundPool 对象并将其传递给构造函数即可。

    【讨论】:

      【解决方案2】:

      您需要一个上下文来使用这些方法。 getSystemService 是上下文实例myActivity.getSystemService() 的一个方法。 load() 还希望您将 Context 实例 (myActivity) 作为第一个参数传入。不建议您在主活动之外保留对上下文的引用,因此您应该考虑将此逻辑移回活动中。你为什么要在单例中这样做?在后台播放音乐?使用服务。

      【讨论】:

      • 不,只是在后台加载音乐...然后从每个活动中调用相同的音乐
      【解决方案3】:

      方法加载需要Context 的实例(即ActivityService)。由于您的单例没有该实例,因此您需要先设置一个 Context 的实例,然后才使用该实例调用 load 方法。

      因此,您不能在构造函数中执行此操作。

      【讨论】:

      • 那么我在哪里做呢?这不是我的代码,而是来自 SO 的“帮助代码”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      相关资源
      最近更新 更多