将数据从Activity传递到同一活动中在webView上加载的HTML文件中使用的JavaScript

时间:2016-06-15 21:29:11

标签: java android android-layout android-intent webview

我的Android应用目标是扫描条形码/二维码并将其传递给在webView元素中加载的HTML文件。

该应用只有一个布局,包含一个按钮和webview元素。 单击按钮后,应用程序打开条形码/ 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();
    }
}

我阅读了thisthis以及thisthis以及this并获得了以下文件:

JavaScriptInterface.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中没有任何内容,只有白页!!白页始终,从启动开始,扫描完代码后!

知道我迷路的地方,以及如何解决它!

注意我需要将数据发送到同一活动中在webView上加载的HTML文件中使用的JavaScript,而不仅仅是发送要加载的URL。

Application tree

2 个答案:

答案 0 :(得分:4)

在阅读thisthis以及this后,我发现我的案例可归纳如下:

  1. 在Android应用程序中将变量从类传递到另一个(即Java类)
  2. 在WebView
  3. 加载的HTML文件中从JavaScript调用Android功能
  4. 将参数从Android类发送回JavaScript
  5. 因此,解决方案可归纳如下:

    1. 创建可与JavaScript命令交互的JavaScriptInterface
    2. 在与JavaScript交互所需的每个功能之前使用@JavascriptInterface注释
    3. 在JavaScript文件中定义要用作module的JavaScript交互的名称:myWebView.addJavascriptInterface(new JavaScriptInterface(this), "module");在此语句中,module是要在javaScript中调用的名称模块归档为module.function()
    4. 使用gettersetter在Android类之间进行通信。
    5. 我的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>
      

      Final App app结构是: enter image description here

      并且在阅读This QR code时。

答案 1 :(得分:0)

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

  $("#itemContainer .listview_tile:last")//see below
   .click(function(){// when you click
      //**this** is span.listview_tile
      //its text comes to <input id="tweetContainer" />
      $("#tweetContainer").val($(this).text());
      //add / remove class displayTable 
      $("#loading").toggleClass('displayTable');
      //show with fadeTo effect 
     $("#loading").fadeTo("fast", 0.95);
});               

<div id="itemContainer ">
   <span class="listview_tile">one</span>
   <span class="listview_tile">two</span><!--$("#itemContainer .listview_tile:last") -->
   <input type="text" id="tweetContainer" />
</div>
<div id="loading">Loading something</div>

然后在你的WebViewActivity中,在调用super.onCreate()之后通过执行此操作来恢复数据:

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