我有以下场景:
- 点击链接或按钮。
- 通过ZXing打开条形码扫描器。
- 扫描代码。
- 将解码数据传递给其他网页。
成功实现了它,需要在JavascriptInterface中添加调用Intent的代码,并且不应该将onActivityResult用于获取已解码内容。
示例代码如下:
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");
}
}
}
}
function scan(){
Android.scanBarcode();
}