原生App植入React Native 踩坑記
為什么我踩坑了
有一個需求要去可以在當(dāng)前工程的feature/RN 下體驗(yàn)下,首頁有一個React Native 的按鈕Click 跳轉(zhuǎn)到一個純RN的九宮格頁面;
工程目錄結(jié)構(gòu)(建議用WebStorm建一個工程對比)
├── android
├── index.android.js
├── index.ios.js
├── ios
├── js
├── node_modules
├── npm-debug.log
├── package.json
└── tests
環(huán)境搭建
混合構(gòu)建
NO.1
minSdk >= 16
support v4包必須23.0.1《绊铩(沒試過其他包版本需不需要牙咏,我統(tǒng)一都設(shè)置成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" 注意和官網(wǎng)教程不一定一致
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 繪制權(quán)限問題 6.0以上必須設(shè)置
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 調(diào)用 native java 代碼類似于Toast StartActivity
此處需要強(qiáng)烈說明片酝,在網(wǎng)上很多教程并不是可行的(包括官網(wǎng)我認(rèn)為都不是很好,我也沒成功),尷尬.所以我閱讀了源碼,追蹤仿照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 = "沒有數(shù)據(jù)";
}
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());
}
}
}
- 創(chuàng)建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目錄下創(chuàng)建StartActivityAndroid.js文件
'use strict';
import { NativeModules } from 'react-native';
module.exports = NativeModules.StartActivityAndroid;
在需要用的地方導(dǎo)入import ToastAndroid from './js/ToastAndroid';
跳轉(zhuǎn)
StartActivityAndroid.startActivityFromJS("com.daigou.selfstation.activity.SearchParcelActivity", "");
No.5 Release sign Apk
關(guān)鍵命令
$ 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;
未完待續(xù)......