Search code examples
androidandroid-webviewbarcode-scanner

How to call Barcode Scanner in Webview, and passing it back?


I have following scenario:

  1. Click a link or button.
  2. Open up Barcode Scanner by ZXing.
  3. Scan the code.
  4. Pass the decoded data to other webpages.

For 1 and 4, it must be performed inside WebView. The problem I faced was, using this https://code.google.com/p/zxing/wiki/ScanningFromWebPages, I will be opening the webpage in default browser. Should I use Intent instead to overcome this problem? Or there are any better workaround?


Solution

  • Successfully got it working, need put add code to call Intent in JavascriptInterface, and the onActivityResult to retrieve decoded contents should not be put inside JavascriptInterface.

    Sample code:

    public class MainView extends Activity {
        private WebView webView;
        public static String barcode = null;
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.webview);
    
            webView = (WebView) findViewById(R.id.webView1);    //you might need to change webView1
    
            webView.getSettings().setJavaScriptEnabled(true);   
            webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
    
            webView.setWebViewClient(new WebViewClient()); 
        } // onCreate();
    
        public class JavaScriptInterface {
            Context mContext;
    
            // Instantiate the interface and set the context
            JavaScriptInterface(Context c) {
                mContext = c;
            }
    
            // using Javascript to call the finish activity
            public void closeMyActivity() {
                finish();
            }
    
            public void scanBarcode() {
                Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                intent.setPackage("com.google.zxing.client.android");
                startActivityForResult(intent, 0);
            }
        }   //JavascriptInterface
    
        public void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == 0) {
                if (resultCode == RESULT_OK) {
                    //here is where you get your result
                    barcode = intent.getStringExtra("SCAN_RESULT");
                }
            }
        }
    
    }
    

    In your Javascript:

    function scan(){
        Android.scanBarcode();
    }