我正在尝试在用户按下html中的按钮时启动条形码扫描器。但是我遇到了错误:
Uncaught TypeError: Object [object Object] has no method 'scanBarcode'", source: file:///android_asset/www/index.html (49)
这将在 JavaScript 中被调用:
function scanner(){
Android.scanBarcode();
}
现在在Java文件中,我有以下代码,其中声明了函数public class JavaScriptInterface
这是我的MainActivity.java
文件:
public class MainActivity extends Activity {
@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled") @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView)findViewById(R.id.webView);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWebView.setInitialScale(1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(false);
webSettings.setSupportZoom(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
//webView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebChromeClient(new WebChromeClient());
//myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("file:///android_asset/www/index.html");
}
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
String barcode = intent.getStringExtra("SCAN_RESULT");
}
}
}
现在这是我在网上找到的一段代码示例,看起来一切都很好,我最初需要做的唯一一件事就是导入所有必要的库,并定义barcode
变量为字符串类型。
非常感谢任何帮助。或者也许可以使用不同的方法从Web视图中访问条形码扫描功能。
WebAppInterface.java
的文件,在这里我有许多函数,我从我的JavaScript中调用,例如Android.showCategories()
。这是我需要调用我的条形码扫描功能的地方,而不是在MainActivity
中。 这很有道理,但是一些默认函数未定义,例如startActivityForResult(intent, 0);
和常量RESULT_OK
。 对此有什么建议吗? - OniJoshin