software-mansion / react-native-reanimated

React Native's Animated library reimplemented
https://docs.swmansion.com/react-native-reanimated/
MIT License
9.11k stars 1.32k forks source link

Incompatibility with Custom React Native Integration with Existing Android Apps (Crash on launch) #2719

Open wfolini opened 2 years ago

wfolini commented 2 years ago

Description

The last v2.3.0 version introduced an issue that affects Android apps that have a custom React Native integration (see integration-with-existing-apps)

Currently, there is no documentation about how to integrate react-native-reanimated for those kinds of apps. I managed to make it work doing what I show in the code example section, on the main React Native activity.

I was not having any kind of issue with this integration using v2.2.4. After I updated to v2.3.0 I started facing this issue. (See crash on launch capture below)

I also checked where the issue comes from, and as the capture shows, it seems like that it was introduced here. https://github.com/software-mansion/react-native-reanimated/blob/main/android/src/main/java/com/swmansion/reanimated/ReanimatedPackage.java#L70

It can be seen there that is trying to cast to a ReactApplication when instead the ReactInstanceManager builder in this case handles the application context just as Application https://github.com/facebook/react-native/blob/main/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java#L155

Expected behavior

Android app should run correctly.

Actual behavior & steps to reproduce

Android app is crashing on launch. image

Snack or minimal code example

import com.swmansion.reanimated.ReanimatedJSIModulePackage
....
public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication()) // <= Crashing because of this
                .setCurrentActivity(this)
                .setBundleAssetName("index.android.bundle")
                .setJSIModulesPackage(new ReanimatedJSIModulePackage()) // <- Adding reanimated here
                .addPackages(packages)
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
       ...
    }
    ...
}

Example for reproducing this issue

https://github.com/WFolini/custom-rn-with-reanimated

Package versions

Affected platforms

github-actions[bot] commented 2 years ago

Issue validator

The issue is valid!

hstorz commented 2 years ago

My app is also crashing on Android launch since the update to 2.3.0 from 2.2.4. I got following Nullpointer from logcat:

12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.swmansion.reanimated.layoutReanimation.g.r(ReanimatedNativeHierarchyManager.java:1)  
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.facebook.react.uimanager.z0$m.execute(UIViewOperationQueue.java:1)   
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.facebook.react.uimanager.z0$a.run(UIViewOperationQueue.java:19)  
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.facebook.react.uimanager.z0.U(UIViewOperationQueue.java:10)  
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.facebook.react.uimanager.z0.s(UIViewOperationQueue.java:1)   
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.facebook.react.uimanager.z0$j.c(UIViewOperationQueue.java:6) 
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.facebook.react.uimanager.f.a(GuardedFrameCallback.java:1)    
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.facebook.react.modules.core.g$d.a(ReactChoreographer.java:7) 
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.facebook.react.modules.core.a$a$a.doFrame(ChoreographerCompat.java:1)    
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1008)   
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at android.view.Choreographer.doCallbacks(Choreographer.java:809)   
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at android.view.Choreographer.doFrame(Choreographer.java:740)   
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:995) 
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at android.os.Handler.handleCallback(Handler.java:938)  
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at android.os.Handler.dispatchMessage(Handler.java:99)  
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at android.os.Looper.loop(Looper.java:246)  
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at android.app.ActivityThread.main(ActivityThread.java:8633)    
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at java.lang.reflect.Method.invoke(Native Method)   
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)    
12-10 10:14:21.940  usap64  24924   -   E   AndroidRuntime      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)    
DrawGu commented 2 years ago

I also encountered the same issue.

t3chcrazy commented 2 years ago

@hstorz do you have Proguard enabled in your app, I remember facing the same issue and I solved it by adding this rule in my proguard-rules.pro, -keep class com.swmansion.reanimated.** { *; }. Original issue link: #2727

hstorz commented 2 years ago

@t3chcrazy thanks for the reply. I use Proguard but only with this line: -keep class com.facebook.react.turbomodule.* { ; } that is mentioned in the reanimated docu. Will try it with your suggestion.

hstorz commented 2 years ago

@hstorz do you have Proguard enabled in your app, I remember facing the same issue and I solved it by adding this rule in my proguard-rules.pro, -keep class com.swmansion.reanimated.** { *; }. Original issue link: #2727

This fixed it for me. Tried with reanimated 1.3.1 on android release build. Thanks again!

halaei commented 2 years ago

Adding -keep to Proguard didn't fixed it for me. I downgraded to 2.2.4.

wfolini commented 2 years ago

This doesn't have anything to do with Proguard. It's an issue that exists whenever the android app uses ReactInstanceManager to build the React Native activity.

tswicegood commented 2 years ago

@WFolini do you have any additional info or related tickets you could include? Been seeing issues like this and have had a hard time tracking it down.

wfolini commented 2 years ago

@tswicegood Here's a repo with a small android app to reproduce this issue https://github.com/WFolini/custom-rn-with-reanimated

dreson4 commented 2 years ago

You'll have to edit your Application file and implement ReactApplication class. Here is mine

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }

      };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
  }

  /**
   * Loads Flipper in React Native templates. Call this in the onCreate method with something like
   * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
   *
   * @param context
   * @param reactInstanceManager
   */
  private static void initializeFlipper(
      Context context, ReactInstanceManager reactInstanceManager) {
    if (BuildConfig.DEBUG) {
      try {
        /*
         We use reflection here to pick up the class that initializes Flipper,
        since Flipper library is not available in release mode
        */
        Class<?> aClass = Class.forName("com.easywallet");
        aClass
            .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
            .invoke(null, context, reactInstanceManager);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
}

And link it in your AndroidManifest.xml file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.kiliwallet">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
      android:name=".MainApplication".    <- add this, name corresponds to the class name of Applicatoin
      ....other stuff here
       >
                 <other activities here>
    </application>
</manifest>
saghul commented 2 years ago

Rn can be used to build libraries too. It might not be desirable / possible for certain apps to implement ReactApplication.

Legion2 commented 1 year ago

We build a library which exposes UI as RN Fragments, we not control the activity and application and can not force users of the fragment to implement ReactApplication.

duannianwww commented 1 year ago

I also encountered the same issue,How to fix this error?

ratz6 commented 1 year ago

It works if we change our mainApplication file accordingly, but how do we achieve this by only changing our Activity file ? @WFolini how'd you go ahead with it ?

wfolini commented 1 year ago

In https://github.com/software-mansion/react-native-reanimated/pull/2863 I explain the way that you can make it work by applying a different mechanism to infer the ReactInstanceManager instance needed for react-native-reanimated. Have you guys tried it?

In this example code below, on getReactInstanceManager method, you guys have to implement by yourself the MainActivity.getReactInstanceManager(), or simply just return mReactInstanceManager

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {

    private static ReactInstanceManager mReactInstanceManager;
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       ...
        List<ReactPackage> packages = new PackageList(getApplication()).getPackages();

        // Adding manually Reanimated package here, with overriding getReactInstanceManager method
         packages.add(new ReanimatedPackage() {
            @Override
            public ReactInstanceManager getReactInstanceManager(ReactApplicationContext reactContext) {
               // Implement here your way to get the ReactInstanceManager
               return MainActivity.getReactInstanceManager();
            }
         });

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setCurrentActivity(this)
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .setJSIModulesPackage(new ReanimatedJSIModulePackage()) // Adding ReanimatedJSIModulePackage here
                .addPackages(packages)
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

        ...
    }
...
}
AlanSl commented 1 year ago

@WFolini Thanks for this. Do you know what should replace the .setJSIModulesPackage(new ReanimatedJSIModulePackage()) part in React Native Reanimated 3.x with Fabric, now that ReanimatedJSIModulePackage has been removed?

I'm trying to adapt this to work in a React Fragment in a custom integration with new architecture enabled, and it gives this error, which I think is another new instance of this underlying issue (Reanimated doing some brittle under the hood auto-apply magic that assumes the default React Native android native app is being used):

com.facebook.react.uimanager.ReanimatedUIManager cannot be cast to com.facebook.react.fabric.FabricUIManager

AlanSl commented 1 year ago

What worked for me here was, copying from the Reanimated / Fabric example repo - in particular, its MainActivity) which seems to include some changes since React Native 0.71 that are expected/essential but not mentioned in the out-of-date React Native app integration documentation?

The crucial one for me was adding this (this is my Kotlin adaptation of the linked example's Java plus a few tweaks to make it fit):

    protected open fun createReactActivityDelegate(): ReactActivityDelegate? {
        return DefaultReactActivityDelegate(
            this as ReactActivity, // My activity class more complex than `extends ReactActivity` so needed `as`
            "my-main-component-name",  // Taken from the "name" field in `app.json` in react native app root dir
            DefaultNewArchitectureEntryPoint.fabricEnabled,
            DefaultNewArchitectureEntryPoint.concurrentReactEnabled
        )
    }

This makes builds work, but I'm then getting errors caused by components missing stateNode so I suspect there's something else essential too.

Eli-Nathan commented 1 year ago

I couldn't get this solution to work. Since ReanimatedJSIModulePackage has been deprecated, I tried to implement the solution posted above without the .setJSIModulesPackage but the error still remains:

MyApplication cannot be cast to com.facebook.react.ReactApplication

I'm trying with react-native-reanimated v3.4.1 and react-native v0.68.5

Any more advice?

Latropos commented 11 months ago

@WFolini I was unable to build the app from reproduction, however you've merged your PR https://github.com/software-mansion/react-native-reanimated/pull/2863 with claim in the description that this problem gets fixed there. So I probably can close it as completed

poprapas commented 9 months ago

but i still this issues Error: Exception in HostFunction: java.lang.ClassCastException: com.facebook.react.uimanager.ReanimatedUIManager cannot be cast to com.facebook.react.fabric.FabricUIManager, js engine: hermes

platform os == android error, but ios work

how to fix? my mainActivity.kt package myproject

import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate

class MainActivity : ReactActivity() {

/**

help me, please

ko-devHong commented 8 months ago

@Latropos Why isn't the solution to this part written in the document?

ko-devHong commented 8 months ago

@wfolini v3 module ReanimatedJSIModulePackage has been deprecated

hi-zp commented 8 months ago

same issue on RN 0.73.6 reanimated 3.8.1

hi-zp commented 8 months ago

@ko-devHong i temporary fixed this, here is my code:

    private ReactInstanceManager mReactInstanceManager;

    protected CustomReactNativeHost(Application application) {
        super(application);
    }

    @Override
    public ReactInstanceManager getReactInstanceManager() {
        if (this.mReactInstanceManager == null) {
            ReactMarker.logMarker(ReactMarkerConstants.INIT_REACT_RUNTIME_START);
            ReactMarker.logMarker(ReactMarkerConstants.GET_REACT_INSTANCE_MANAGER_START);
            this.mReactInstanceManager = this.createReactInstanceManager();
            ReactMarker.logMarker(ReactMarkerConstants.GET_REACT_INSTANCE_MANAGER_END);
        }

        return this.mReactInstanceManager;
    }

    @Override
    public boolean hasInstance() {
        return this.mReactInstanceManager != null;
    }

    @Override
    public void clear() {
        if (this.mReactInstanceManager != null) {
            this.mReactInstanceManager.destroy();
            this.mReactInstanceManager = null;
        }
    }

    @Override
    public boolean getUseDeveloperSupport() {
        return false;
    }

    @Override
    protected List<ReactPackage> getPackages() {
        return null;
    }
}

public class MyApplication extends Application implements ReactApplication {
  @NonNull
  @Override
  public CustomReactNativeHost getReactNativeHost() {
    CustomReactNativeHost host = new CustomReactNativeHost(this) {
      @Override
      public boolean getUseDeveloperSupport() {
        return BuildConfig.DEBUG;
      }

      @Override
      protected List<ReactPackage> getPackages() {
        return packages;
      }

      @Nullable
      @Override
      protected DevSupportManagerFactory getDevSupportManagerFactory() {
        return super.getDevSupportManagerFactory();
      }

      @Override
      protected String getJSMainModuleName() {
        return "index";
      }

      @Nullable
      @Override
      protected JavaScriptExecutorFactory getJavaScriptExecutorFactory() {
        return new HermesExecutorFactory();
      }
    };
    return host;
  }
 。。。balabala
}
yzhe554 commented 4 months ago

Please reopen the issue @Latropos The mentioned solution is with setJSIModulesPackage but it's removed in the new RNReanimated package.