2013-12-10 66 views
0

我正在開發Android應用程序,通過使用Zxing條形碼閱讀器插件來讀取條形碼。試圖從Java調用JavaScript函數源代碼

在插件中有一個名爲window.plugins.barcodeScanner的對象,我們使用該對象對條碼進行編碼/解碼。

我不想用HTML來調用東西,而是想從Java調用下面的Javascript函數[點擊圖片 - 下面的函數將被調用]。

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); 
     } 
    ); 
} 

請讓我知道如何做到這一點。

+1

有用於在Java中運行JavaScript的庫。犀牛想到。然而,我懷疑你會得到'windows''的東西,因爲沒有'window'範圍,因爲它來自瀏覽器。您的其他選擇可能是以某種方式使用Java瀏覽器小部件,以便IT代表應用程序加載頁面。 – CodeChimp

+0

您的應用程序是否爲phonegap應用程序,或者您正試圖在嚴格原生應用程序中單獨使用插件? –

+0

@UnchartedSpace:這完全是一個本機應用程序,並單獨使用插件。 –

回答

1

假設:

您只需將掃描和onActivityResult方法以及https://github.com/wildabeast/BarcodeScanner/blob/master/src/android/com/phonegap/plugins/barcodescanner/BarcodeScanner.java中的一些幫助字符串拉出並放入您的活動中即可。您需要用您自己的活動替換對cordova的引用。

最終的結果可能是這個樣子:

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 
     } 
    } 
} 

是否適合你,那你甚至不需要科爾多瓦作爲扶養。

+0

是的。它有幫助,這是我的預期。多謝!!非常感謝你。 –

0

您可以使用CordovaWebView中定義的sendJavascript函數從Android本地端調用Javascript代碼。

在你的情況下,你會做這樣的事情。考慮到要調用下面的函數:

function scanSuccessCallback(result) { //do something }

在你的插件本機端:

this.webView.sendJavascript("scanSuccessCallback('the result');");