Reputation: 608
I am developing an Android App to read the barcode by using the Zxing Barcode reader Plugin.
In the plugin there is an object named window.plugins.barcodeScanner with which we encode/decode the barcode.
I don't wanna use HTML to invoke things instead want the below Javascript function to be called from Java [on click of the image- the below function would be invoked].
function scanCode(){
window.plugins.barcodeScanner.scan(
function(result){
alert("Scanned Code: " + result.text
+ ". Format: " + result.format
+ ". Cancelled: " + result.cancelled);
},
function(error){
alert("Scan failed: " + error);
}
);
}
Kindly let me know how to achieve this.
Upvotes: 0
Views: 173
Reputation: 861
Assumptions:
All you have to do is pull out the scan and onActivityResult methods and some of the helper strings from https://github.com/wildabeast/BarcodeScanner/blob/master/src/android/com/phonegap/plugins/barcodescanner/BarcodeScanner.java and put them in your activity. You'll need to replace the references to cordova with your own activity.
End result may look something like this:
public static final int REQUEST_CODE = 0x0ba7c0de;
private static final String SCAN_INTENT = "com.google.zxing.client.android.SCAN";
public void scan() {
Intent intentScan = new Intent(SCAN_INTENT);
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
this.startActivityForResult(intentScan, REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String barcode = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
//Do whatever you need with the barcode here
} else if (resultCode == Activity.RESULT_CANCELED) {
// handle a canceled scan
} else {
// throw an error or something
}
}
}
If that works for you, then you don't even need cordova as a dependancy.
Upvotes: 1
Reputation: 1792
You can invoke Javascript code from native side on Android using the sendJavascript function defined in CordovaWebView.
In your case you would do something like this. Considering that the you want to call the following function:
function scanSuccessCallback(result) {
//do something
}
on the native side in your plugin:
this.webView.sendJavascript("scanSuccessCallback('the result');");
Upvotes: 0