我的 Android 应用程序目标是扫描条形码/QR 码并将其传递到在 webView 元素加载的 HTML 文件。
该应用只有一个布局,其中包含一个按钮和 webview 元素。 单击按钮后,应用程序会打开条形/QR 扫描器并将结果返回到 Activity ,我需要将此结果传递到我的 HTML 文件以进行进一步处理。
MainActivity 工作正常,如 this 所示tutorial,并在这里返回结果:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
/*** I NEED to SEND the 'scanContent' to the my HTML file loaded at the WebView element ***/
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
我读了this和 this和 this和 this和 this并获得以下文件:
JavaScript接口(interface).java
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
和 WebViewActivity.java:
public class WebViewActivity extends Activity {
// private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView)findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
/*** I think something wrong in this area **/
webView.loadUrl("file:///android_asset/myFile.html");
webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
view.loadUrl("javascript:init('" + url + "')");
}
});
//webView.loadUrl("http://www.google.com");
// String customHtml = "<html><body>" +
// ""+
// "</body></html>";
// webView.loadData(customHtml, "text/html", "UTF-8");
}
Android Studio IDE 中没有出现错误,运行应用程序时扫描按钮工作,但 webview 中没有出现,只有白页!!一直是白页,从开机到扫码后!
知道我在哪里迷路了,以及如何解决它!
注意我需要将数据发送到同一 Activity 中在 webView 加载的 HTML 文件中使用的 JavaScript,而不仅仅是发送要加载的 URL。
最佳答案
看完this和 this和 this ,我发现我的案例可以总结为以下几点:
- 在 Android 应用程序中将变量从一个类传递到另一个类(即 Java 类)
- 从 WebView 加载的 HTML 文件中的 JavaScript 调用 Android 函数
- 将参数从 Android 类发送回 JavaScript
因此,解决方案可以总结如下:
- 创建可以与 JavaScript 命令交互的
JavaScriptInterface
类 - 在与 JavaScript 交互所需的每个函数之前使用
@JavascriptInterface
注释 - 在 JavaScript 文件中定义要用作
module
的 JavaScript 交互的名称:myWebView.addJavascriptInterface(new JavaScriptInterface(this), "module");
在此语句中,module
是要在 javaScript 文件中作为module.function()
调用的名称模块
- 使用
getter
和setter
在 Android 类之间进行通信。
我的 MainActivity.java
文件变成了这样:
package com.fonix.qr;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn;
private TextView formatTxt, contentTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scanBtn = (Button) findViewById(R.id.scan_button);
formatTxt = (TextView) findViewById(R.id.scan_format);
contentTxt = (TextView) findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.addJavascriptInterface(new JavaScriptInterface(this), "fonix");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
}
public void onClick(View v) {
if (v.getId() == R.id.scan_button) {
scanCode();
// IntentIntegrator scanIntegrator = new IntentIntegrator(this);
// scanIntegrator.initiateScan();
}
}
public void scanCode(){
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public String scanContent;
public String scanFormat;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
scanContent = scanningResult.getContents();
scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
public String getContent(){ return scanContent; }
public class JavaScriptInterface {
Context mContext;
/* Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/* Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public void scanJS() {
scanCode();
}
@JavascriptInterface
public String scanResult() {
return getContent();
}
}
}
assets -> index.html
文件是:
<!DOCTYPE html>
<html>
<head>
<title>QR and BarCode Scanner using both Android Native and JavaScript Functionality</title>
</head>
<body>
Hello Android! <br/>
<br/>
The above button in Native Android, while the below one is JavaScript button. <br/>
<br/>
<input type="button" value="Scan from JavaScript button" onClick="scan()" />
<br/>
<br/>
<br/>
Below button will show the latest scan result, regardless read through Native Android button, or JavaScript button, and will display the result as Native Android Toast.
<br/>
<br/>
<input type="button" value="Show Scan result" onClick="showScanResult()" />
</body>
<script type="text/javascript">
function scan() {
fonix.scanJS();
}
function showScanResult() {
var scanResult = fonix.scanResult();
// (!scanResult) equal === null or === undefined
if(!scanResult)fonix.showToast("Nothing had been scanned");
else fonix.showToast(fonix.scanResult());
}
</script>
</html>
layout -> activity_main.xml
文件是:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.fonix.qr.MainActivity">
<Button android:id="@+id/scan_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/scan"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:id="@+id/scan_format"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true"
android:layout_below="@id/scan_button"
android:layout_alignEnd="@+id/scan_button" />
<TextView
android:id="@+id/scan_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true"
android:layout_below="@+id/scan_format"
android:layout_alignEnd="@+id/webview" />
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/webview"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_below="@+id/scan_content" />
</RelativeLayout>
values -> strings.xml
文件是:
<resources>
<string name="app_name">QR and BarCode reader</string>
<string name="scan">Scan from Native Android button</string>
</resources>
AndroidManifest.xml
文件是:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fonix.qr">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
关于java - 将数据从 Activity 传递到同一 Activity 中在 webView 加载的 HTML 文件中使用的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37846098/