Wednesday, June 29, 2016

Adding packages if your MainActivity extends ReactActivity

I was recently trying to get some audio to play in my App. I was trying to use react-native-audioplayer because it works in both Android and iOS. The instructions include the following:

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
  ...

  @Override
  protected void onCreate(Bundle savedInstanceState){
    ...
    mReactInstanceManager = ReactInstanceManager.builder()
      .setApplication(getApplicatio)
      ...
      .addPackage(new MainReactPackage())
      .addPackage(new RNAudioPlayer())   //  <--- add here 
      ...
  }
}

So pretty simple - just add the RNAudioPlayer package to the ReactInstanceManager builder and we're good to go, right?

Except that my MainActivity doesn't contain an onCreate method or any of the code in it. I originally thought I just needed to create this method and add code to it, until I realised that the example was extending from Activity and my class was extending from ReactActivity.

The builder already exists in ReactActivity, and to add a package you just need to add it to the getPackages method, like so:

@Override
protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
        new MainReactPackage(),
        new RNAudioPlayer()
    );

}

No comments:

Post a Comment