hirbod / react-native-volume-manager

React Native module which adds the ability to change the system volume on iOS and Android, listen to volume changes and supress the native volume UI to build your own volume slider or UX. It can listen to iOS mute switch and ringer mode changes on Android (and let you set the ringer mode)
MIT License
216 stars 14 forks source link

Android: VolumeManagerModule setupKeyListener NullPointerException error #32

Open arekm213 opened 3 months ago

arekm213 commented 3 months ago

We are getting a lot of error reports like this in our app which uses your library:

Exception java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window android.app.Activity.getWindow()' on a null object reference
  at com.reactnativevolumemanager.VolumeManagerModule.lambda$setupKeyListener$1$com-reactnativevolumemanager-VolumeManagerModule (VolumeManagerModule.java:90)
  at com.reactnativevolumemanager.VolumeManagerModule$$ExternalSyntheticLambda2.run
  at android.os.Handler.handleCallback (Handler.java:958)
  at android.os.Handler.dispatchMessage (Handler.java:99)
  at android.os.Looper.loopOnce (Looper.java:205)
  at android.os.Looper.loop (Looper.java:294)
  at android.app.ActivityThread.main (ActivityThread.java:8248)
  at java.lang.reflect.Method.invoke
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:552)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:971)

Could you please think about proper fix for this? We are currently early returning in setupKeyListener method if mContext.getCurrentActivity() returns null, but this probably could be handled better This happens on "react-native": "0.68.7", unfortunately im not able to reproduce this issue myself

hgapsilva commented 2 months ago

in the file a/node_modules/react-native-volume-manager/android/src/main/java/com/reactnativevolumemanager/VolumeManagerModule.java b/node_modules/react-native-volume-manager/android/src/main/java/com/reactnativevolumemanager/VolumeManagerModule.java , in the setupKeyListener method you can add a condition to see if the mContext exists, like this:

private void setupKeyListener() {
     runOnUiThread(() -> {

       if (mContext.getCurrentActivity() == null) return;

       View rootView =
       ... 
}

While you won't have this fix in the lib, you can make this change and then use this command in your project's terminal:

npx patch-package react-native-volume-manager

this will create a patch with the changes (the file shouldn't be large when created, it should only have the changes) and whenever you install node_modules it will use this patch to make your change.

this error is similar to this one:

https://github.com/hirbod/react-native-volume-manager/pull/28