美文网首页
原生App 植入 React Native 踩坑记

原生App 植入 React Native 踩坑记

作者: SheepYan9 | 来源:发表于2018-03-08 10:06 被阅读21次

原生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

  • minSdk >= 16

  • support v4包必须23.0.1 (没试过其他包版本需不需要,我统一都设置成23.0.1 也就是说,23.0.1之后的一些新功能就不能用了,毕竟鱼和熊掌不可得兼;) 终极所有support v4 版本解决办法

    subprojects {
      configurations.all {
          resolutionStrategy {
              // https://github.com/facebook/react-native/issues/6152
              force 'com.android.support:support-v4:23.0.1'
          }
      }
    }
    
    

NO.2

  • Maven

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

  • adb 端口问题

    adb reverse tcp:8081 tcp:8081
    
    

NO.4

  • Debug 绘制权限问题 6.0以上必须设置

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
       if (!Settings.canDrawOverlays(this)) {
          Intent intt = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
          Uri.parse("package:" + getPackageName()));
          startActivityForResult(intt, 1234);
      }else{
          Intent ii = new Intent(this, MyReactActivity.class);
          ii.putExtra("data", LoginManager.getUserType());
          startActivity(ii);
      }
    }else{
      startActivity(new Intent(this, MyReactActivity.class));
    }
    
    

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

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

  • 第一个文件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());
        }
    }
}

  • 创建MyReactPackage extends LazyReactPackage
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();
    }
}

  • 把MyReactPackage 添加到packages中 addPackage(new MyReactPackage())
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中使用JAVA代码

在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

  • 官方的教程 http://reactnative.cn/docs/0.26/signed-apk-android.html#content

  • 关键命令

    $ mkdir -p android/app/src/main/assets //千万别忘了
    $ react-native bundle --platform android --dev false --entry-file index.android.js \
    --bundle-output android/app/src/main/assets/index.android.bundle \
    --assets-dest android/app/src/main/res/
    $ cd android && ./gradlew assembleRelease
    
    

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.** { *; }

  • 增加ReactNative 的包的大小会比原来大5M; 未完待续......

相关文章

网友评论

      本文标题:原生App 植入 React Native 踩坑记

      本文链接:https://www.haomeiwen.com/subject/tcbefftx.html