5

I would like to know how can I force volume buttons to only control media while in my application.

I know this is an android specific question and ios does this by default.

There are two related questions giving android solutions:

Volume Control in android application

How can I manage audio volumes sanely in my Android app?

They both suggest adding setVolumeControlStream(AudioManager.STREAM_MUSIC); to android but I'm a react-native developer and not familiar with java.

There is also this react-native related question:

How to control media volume?

Which gives me no idea on where onCreate() is.

Any Specific suggestions on where to add this line in java part of react-native?

Ahmad Maleki
  • 1,415
  • 3
  • 21
  • 35
  • 1
    İf you created your app via react-native-cli (not expo) you can open android project on Android Studio and add 'setVolumeControlStream(AudioManager.STREAM_MUSIC);' line to your onCreate method at MainActivity. But in Expo that is impossible. – VolkanSahin45 Mar 01 '18 at 09:10
  • @VolkanSahin45 Thank you sir, this helped a lot – Ahmad Maleki Mar 03 '18 at 08:09

1 Answers1

5

So I did some research and thanks to @VolkanSahin45 for his comment, I figured it out.

Adding setVolumeControlStream(AudioManager.STREAM_MUSIC); was right.

What I had to do was to Override the onCreate() function inside MainActivity.java.

public class MainActivity extends ReactActivity {
    /* Any previous code you had here */
    [...]

    /* Override the onCreate function here */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        /* Add this line to keep the original behavior of onCreate() */
        super.onCreate(savedInstanceState);
        /* This one does the trick */
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    }
}
Ahmad Maleki
  • 1,415
  • 3
  • 21
  • 35