Communication b/w React Native & Native Android threads with a callback response to React Native
In this topic, we are going to know how to integrate a native module into react native and get a callback response from the android thread to react-native bypassing params to the native android thread
Steps involved in the integration
- Create an Activity class where we perform our native activity
- Create a Manager class to call activity class
- Create a Package class to register the manager class with the native thread
- Register package class with main application .java file
- Do necessary changes to the androidManifest.xml page
Create an Activity class
Create a MyActivity.kt file that perform the native functionality
override fun onCreate(savedInstanceState: Bundle?) {
.
. code to
.
.
startActivity(launchIntent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
PosManager.invokeCallback(amount?:””,orderId?:””,status?:””)
}
Create a Manager class to call activity class
Create a companion object which receives callback response
companion object {
var cb : Callback? = null
fun invokeCallback(amount : String, orderId : String, status : String) {
cb?.invoke(amount, orderId, status)
}
}
fun StartPosApp(orderId: String, amount: String,payMode: String, callback :Callback) {
val intent = Intent(reactApplicationContext, MyActivity::class.java)
cb = callback
reactApplicationContext.startActivity(intent)
}
Create a Package class
class MyPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
val modules = ArrayList<NativeModule>()
modules.add(MyManager(reactContext))
return modules
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return Collections.emptyList<ViewManager<*, *>>()
}
}
Register package class with mainApplication .java
Add this line in mainapplication.java to register package to invoke function
packages.add(new PosPackage());
changes to manifest.xml
add this activity to get callbacks and invokation to app
<activity android:exported=”true” android:launchMode=”singleTask” android:name=”.myproject.MyActivity”>
<intent-filter>
<category android:name=”android.intent.category.DEFAULT” />
</intent-filter>
</activity>
Expose and invoking
import {NativeModules} from ‘react-native’;
NativeModules.PosModule.StartPosApp(
date,
amt,
‘All’,
(amount, orderId, status) => {
console.log(amount, orderId, status);// here we are getting response back to react native from main thread
);