The example in this article shares the specific code for sending messages and jumping from the js interface to the native interface for your reference. The specific content is as follows
Step 1
In idea, open ./Android/app under the rn project, this process It will take a while, and you may also need to download gradle dependencies or something.
Step 2
It’s the same as making a native app. We create a new TestActivity. For simplicity, we only implement it as follows:
public class TestActivity extends AppCompatActivity { private Button mBtGoBack; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); mBtGoBack = (Button) findViewById(R.id.bt_go_back); mBtGoBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } }
Step 3
Write a class ExampleInterface extends ReactContextBaseJavaModule and receive messages in this class.
Specific code:
public class ExampleInterface extends ReactContextBaseJavaModule { private ReactApplicationContext mRApplicationContext; public ExampleInterface(ReactApplicationContext reactContext) { super(reactContext); mRApplicationContext = reactContext; } //RN使用这个名称来调用原生模块的其他函数 @Override public String getName() { return "ExampleInterface"; } //必须写@ReactMethod,将其注册为能够被React调用的函数 @ReactMethod public void HandlerMessage(String aMessage){ Log.d("lt","====receive message from RN==="+aMessage); //这部分实现简单的跳转 Intent intent = new Intent(mRApplicationContext,TestActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mRApplicationContext.startActivity(intent); } }
Step 4
Implement a package manager and register the class ExampleInterface that receives the message.
The code is as follows:
public class AnExampleReactPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactApplicationContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new ExampleInterface(reactApplicationContext)); return modules; } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) { return Collections.emptyList(); } }
Step 5
Add the package management class AnExampleReactPackage in MainApplication;
@Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new AnExampleReactPackage() ); }
Step 6
In the js interface, send a message;
buttonPress:function(){ NativeModules.ExampleInterface.HandlerMessage('test'); }