前言
RN作为混合开发,肯定需要与原生直接的页面跳转,这里也属于和原生端通信的知识模块。我们知道Android的页面跳转是通过Intent、Rn是通过路由,而两者直接页面互相跳转就需要原生借助JS暴露接口给Rn来实现了。先上效果图:
运行项目:React Native 配置环境,运行第一个RN项目
集成项目:React Native 教程——集成到现有原生应用
第一步,AS创建一个Activity,显示HelloWorld:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(createView());
}
private View createView() {
LinearLayout ll= new LinearLayout(this);
ll.setGravity(Gravity.CENTER);
ll.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
// 设置文字
TextView mTextView = new TextView(this);
mTextView.setText("hello world");
LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// 在父类布局中添加它,及布局样式
ll.addView(mTextView, mLayoutParams);
return ll;
}
第二步,创建MyIntentModule类,并继承ReactContextBaseJavaModule。
注意:方法头要加@ReactMethod
/**
* 原生Activity与React交互——模块
*/
public class MyIntentModule extends ReactContextBaseJavaModule {
public MyIntentModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "IntentMoudle";
}
//注意:记住getName方法中的命名名称,JS中调用需要
@ReactMethod
public void startActivityFromJS(String name, String params){
try{
Activity currentActivity = getCurrentActivity();
if(null!=currentActivity){
Class toActivity = Class.forName(name);
Intent intent = new Intent(currentActivity,toActivity);
intent.putExtra("params", params);
currentActivity.startActivity(intent);
}
}catch(Exception e){
throw new JSApplicationIllegalArgumentException(
"不能打开Activity : "+e.getMessage());
}
}
@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());
}
}
//注意:startActivityFromJS、dataToJS方法添加RN注解(@ReactMethod),否则该方法将不被添加到RN中
}
第三步,创建MyReactPackage类
实现ReactPackage接口暴露给RN调用,在createNativeModules里注册上一步添加的模块:
/**
* 注册模块
*/
public class MyReactPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new MyIntentModule(reactContext));
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}