有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我阅读了thisthisthisthisthis并得到以下文件:

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

Application tree


共 (2) 个答案

  1. # 1 楼答案

    对于发送部分,将其放在MainActivity中,输入您想要输入的值,如下所示:

    Intent sendIntent = new Intent(this, WebViewActivity.class);
    sendIntent.putExtra("webBrowserUrl", "http://www.google.com");
    //add other values to intent as necessary
    startActivity(sendIntent);
    

    然后在您的WebViewActivity中,在调用super之后执行此操作以获取数据。onCreate():

    String url = getIntent().getStringExtra("webBrowserUrl");
    webView.loadUrl(url);
    
  2. # 2 楼答案

    在阅读了thisthisthis之后,我发现我的情况可以总结如下:

    1. 在Android应用程序中将变量从类传递到另一个类(即Java类)
    2. 从WebView加载的HTML文件中的JavaScript调用Android函数
    3. 将参数从Android类发送回JavaScript

    因此,解决方案可以总结如下:

    1. 创建可以与JavaScript命令交互的JavaScriptInterface
    2. 在与JavaScript交互所需的每个函数之前使用@JavascriptInterface注释
    3. 将要在JavaScript文件中用作module的JavaScript交互的名称定义为:myWebView.addJavascriptInterface(new JavaScriptInterface(this), "module");在该语句中,module是要在JavaScript文件中作为module.function()调用的名称模块
    4. 使用gettersetter在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>
    

    最终的应用程序结构是: enter image description here

    This QR code的时候