In this case I'm using the Embedded ZXing library to scan a QR code and return the result to JavaScript land in React Native.
In order to do that we need access to the Activity
instance, which is not usually available to ReactPackage classes.
We'll pass the Activity
into the QRCodeScanPackage when we add it:
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new QRCodeScanPackage(this)) // `this` is the Activity
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
Then in the QRCodeScanPackage we'll need to make sure that the Module also has the Actvity available
QRCodeScanPackage.java
public class QRCodeScanPackage implements ReactPackage {
Activity mActivity;
public QRCodeScanPackage(Activity activity) {
mActivity = activity;
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new QRCodeScanModule(reactContext, mActivity)); //Pass along the `Actviity`
return modules;
}
And then of course the Module now has the Activity
and can use it to initiate the scan (Basically fire an Intent)
QRCodeScanModule.java
public class QRCodeScanModule extends ReactContextBaseJavaModule {
Activity mActivity;
public QRCodeScanModule(ReactApplicationContext reactContext, Activity activity) {
super(reactContext);
mActivity = activity;
}
public String getName(){
return "QRCode";
}
@ReactMethod
public void scan() {
new IntentIntegrator(mActivity).initiateScan();
}
Last but not least, we need to listen for the activity result and pass the scan data back into JS land:
MainActivity.java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String result = data.getStringExtra(Intents.Scan.RESULT);
Log.d("QR", result);
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
if (reactContext != null) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("qrScan", result);
}
}
All the files are included in this gist