原生App 植入 React Native 踩坑记

2018-03-08  本文已影响21人  SheepYan9

原生App 植入 React Native 踩坑记

何祥源 2017年1月18日保存

查看编辑历史

原生App植入React Native 踩坑记

可以在ezdelivery 工程的feature/RN 下体验下,首页有一个React Native 的按钮Click 跳转到一个纯RN的九宫格页面;

工程目录结构(建议用WebStorm建一个工程对比)

├── android ├── index.android.js ├── index.ios.js ├── ios ├── js ├── node_modules ├── npm-debug.log ├── package.json └── tests

环境搭建

混合构建

NO.1

NO.2

url "$rootDir/../node_modules/react-native/android" 注意和官网教程不一定一致


allprojects {
    repositories {
        jcenter()
        maven {
            // All of React Native (JS, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

NO.3

NO.4

NO.5 JS 调用 native java 代码类似于Toast StartActivity

此处需要强烈说明,在网上很多教程并不是可行的(包括官网我认为都不是很好,我也没成功),尴尬.所以我阅读了源码,追踪仿照MainReactPackage和ToastAndroid写了一个StartActivity的Module

    @ReactModule(name = "StartActivityAndroid")
public class StartActivityModule extends ReactContextBaseJavaModule {
    public StartActivityModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "StartActivityAndroid";
    }

    @ReactMethod
    public void dataToJS(Callback successBack, Callback errorBack) {
        try {
            Activity currentActivity = getCurrentActivity();
            String result = currentActivity.getIntent().getStringExtra("data");
            if (TextUtils.isEmpty(result)) {
                result = "没有数据";
            }
            successBack.invoke(result);
        } catch (Exception e) {
            errorBack.invoke(e.getMessage());
        }
    }
    @ReactMethod
    public void startActivityFromJS(String activityPkgName, String params) {
        try {
            Activity currentActivity = getCurrentActivity();
            if (null != currentActivity) {
                Class toActivity = Class.forName(activityPkgName);
                Intent intent = new Intent(currentActivity, toActivity);
                intent.putExtra("params", params);
                currentActivity.startActivity(intent);
            }
        } catch (Exception e) {
            throw new JSApplicationIllegalArgumentException(
                    "不能打开Activity : " + e.getMessage());
        }
    }
}

public class MyReactPackage extends LazyReactPackage {
    @Override
    public List<ModuleSpec> getNativeModules(final ReactApplicationContext reactContext) {
        return Arrays.asList(new ModuleSpec(StartActivityModule.class, new Provider<NativeModule>() {
            @Override
            public NativeModule get() {
                return new StartActivityModule(reactContext);
            }
        }));
    }

    @Override
    public ReactModuleInfoProvider getReactModuleInfoProvider() {
        return LazyReactPackage.getReactModuleInfoProviderViaReflection(this);
    }

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }
}

public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Settings.canDrawOverlays(this);
        }
        mReactRootView = new ReactRootView(this);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                .addPackage(new MyReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);

        setContentView(mReactRootView);
    }
    //......其他代码
}

在js目录下创建StartActivityAndroid.js文件

'use strict';
import { NativeModules } from 'react-native';
module.exports = NativeModules.StartActivityAndroid;

在需要用的地方导入import ToastAndroid from './js/ToastAndroid';

跳转

 StartActivityAndroid.startActivityFromJS("com.daigou.selfstation.activity.SearchParcelActivity", "");

No.5 Release sign Apk

No.6 release包混淆出错 ClassNotFoundException

混淆文件中添加

## react native
# https://github.com/tdzl2003/react-native/blob/39206de9a26185435d16448f8d50142197eee6f3/local-cli/generator-android/templates/src/app/proguard-rules.pro
-keep class * extends com.facebook.react.bridge.JavaScriptModule { *; }
-keep class * extends com.facebook.react.bridge.NativeModule { *; }
-keepclassmembers,includedescriptorclasses class * { native <methods>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.UIProp <fields>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.ReactProp <methods>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.ReactPropGroup <methods>; }

-dontwarn com.facebook.react.**

# okhttp

-keepattributes Signature
-keepattributes *Annotation*
-keep class com.squareup.okhttp.** { *; }
-keep interface com.squareup.okhttp.** { *; }
-dontwarn com.squareup.okhttp.**

# okio

-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-dontwarn okio.**

# stetho

-dontwarn com.facebook.stetho.**

如果还不行的话就再增加

-keep class com.facebook.** { *; }

上一篇 下一篇

猜你喜欢

热点阅读