java - 当我的应用程序运行时,硬件音量按钮不起作用

标签 java android c++ audio

我一直在开发一款播放音频的应用程序。我目前正在将音频作为 STREAM_MUSIC 类型的流播放,效果很好。我希望能够使用设备上的硬件音量控件来控制音量。当我在应用程序中时,硬件按钮不会执行任何操作,音量不会改变, toast 也不会弹出。然后我按下主页按钮,以便应用程序在后台运行硬件音量按钮工作。它们仅在我的应用程序在后台运行时才有效。

我尝试在我的 onCreate() 方法中使用代码 this.setVolumeControlStream(AudioManager.STREAM_MUSIC); 并且这并没有改变应用程序的行为,我是仍然面临同样的问题。

我还在 DROID 2、DROID RAZR、Samsung Galaxy s3、Samsung Galaxy s4、Lenovo 平板电脑和已获得 root 权限的 DROID 2 上进行了测试,但它们的行为都相同。

 public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    setVolumeControlStream(audio.STREAM_MUSIC); //this line should set up the hardware
    //buttons to control the volume 
    if (QtApplication.m_delegateObject != null && QtApplication.onCreate != null) {
        QtApplication.invokeDelegateMethod(QtApplication.onCreate, savedInstanceState);
        return;
    }

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    try {
        m_activityInfo = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
        e.printStackTrace();
        finish();
        return;
    }

    if (null == getLastNonConfigurationInstance()) {
        // if splash screen is defined, then show it
        if (m_activityInfo.metaData.containsKey("android.app.splash_screen") )
            setContentView(m_activityInfo.metaData.getInt("android.app.splash_screen"));
        startApp(true);
    }
}

最佳答案

You may be tempted to try and listen for volume key presses and modify the volume of your audio stream that way. Resist the urge. Android provides the handy setVolumeControlStream() method to direct volume key presses to the audio stream you specify.

看看这个,我认为它可能会有所帮助:
Use Hardware Volume Keys to Control Your App’s Audio Volume

编辑:

在您的 oncreate 方法上,您必须执行以下操作:

 this.setVolumeControlStream(AudioManager.STREAM_MUSIC); //if you use AudioManager.STREAM_MUSIC to load the sound
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
      @Override
      public void onLoadComplete(SoundPool soundPool, int sampleId,
          int status) {
        loaded = true;
      }
    });
   soundPool.load(this, R.raw.sound1, 1); // your sound

关于java - 当我的应用程序运行时,硬件音量按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643241/

相关文章:

c++ - 在 OSX 上更新 GCC

java - 如何在jsf中获取当前 View id和上一个 View id

java - Spring Security 忽略 successHandler 和 failureHandler

用于音频的 Android 事件监听器

c++ - 在 C++ 中使用 qsort 时运行失败错误

c++ - SDL 无法在 native 环境中编译

java - 如何将复杂的map嵌套列表转换为json对象

java - 即使应用程序有子窗口也能保持焦点

java - 在 Java/Android 中显示天数差异

android - 两种方法更新 Android App Widget 有什么区别?