java将数据从活动传递到在同一活动中webView加载的HTML文件中使用的JavaScript
我的Android应用程序的目标是扫描条形码/二维码,并将其传递到webView元素中加载的HTML文件
该应用程序只有一个布局,其中包含一个按钮和webview元素。 单击按钮后,应用程序将打开bar/QR扫描仪并将结果返回到活动,我需要将此结果传递到我的HTML文件以进行进一步处理
MainActivity工作正常,如this教程中所示,并在此处返回结果:
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并得到以下文件:
JavaScriptInterface。爪哇
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。爪哇:
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:///安卓_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中没有显示任何内容,只有白色页面!!白色页面总是,从启动到启动,再扫描代码
知道我在哪里迷路了吗?知道怎么修吗
注意在同一活动中,我需要将数据发送到webView加载的HTML文件中使用的JavaScript,而不仅仅是发送要加载的URL
# 1 楼答案
对于发送部分,将其放在MainActivity中,输入您想要输入的值,如下所示:
然后在您的WebViewActivity中,在调用super之后执行此操作以获取数据。onCreate():
# 2 楼答案
在阅读了this和this和this之后,我发现我的情况可以总结如下:
因此,解决方案可以总结如下:
JavaScriptInterface
类@JavascriptInterface
注释module
的JavaScript交互的名称定义为:myWebView.addJavascriptInterface(new JavaScriptInterface(this), "module");
在该语句中,module
是要在JavaScript文件中作为module.function()
调用的名称模块getter
和setter
在Android类之间进行通信李>我的
MainActivity.java
文件变成这样:并且
assets -> index.html
文件是:layout -> activity_main.xml
文件是:values -> strings.xml
文件是:AndroidManifest.xml
文件是:最终的应用程序结构是:
读的时候