Android Open Source - jsWebView Main Activity






From Project

Back to project page jsWebView.

License

The source code is released under:

Apache License

If you think the Android project jsWebView listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package wjj.js;
//from w  ww .  java2 s.  com
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.URLUtil;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
public class MainActivity extends Activity {
  WebView wv;
  private Button mButton;
  private EditText mEditText;
  private static final String TAG = "MainActivity";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mButton = (Button) findViewById(R.id.button01);
    mEditText = (EditText) findViewById(R.id.edittext01);
    wv = ((WebView) findViewById(R.id.webView1));
    WebSettings ws = wv.getSettings();
    ws.setSupportZoom(true);
    ws.setBuiltInZoomControls(true);
    // ws.setLoadWithOverviewMode(true);
    // ws.setUseWideViewPort(true);
    ws.setDefaultTextEncodingName("utf-8");
    ws.setJavaScriptEnabled(true);
    // ???????js????
    wv.addJavascriptInterface(new MyJavaScriptInterface(), "myjs");
    // ws.setJavaScriptCanOpenWindowsAutomatically(true);// ?????????
    // ???javascript?window.open
    wv.setWebViewClient(new WebViewClient() {
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
      }

      @Override
      public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
      }

      @Override
      public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
      }
    });

    // ???js????
    // wv.setWebChromeClient(new MyWebChromeClient());//js?????1
    wv.setWebChromeClient(new MyWebChromeClient2(MainActivity.this));// js?????2

    wv.loadUrl("file:///android_asset/showtime.html");// ???1
    // wv.loadUrl("file:///android_asset/dialog.html");// ???2
    // wv.loadUrl("javascript:alert('lala')");//????

    mButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        try {
          // ?????????????
          String url = mEditText.getText().toString();
          // ???????????????
          if (URLUtil.isNetworkUrl(url)) {
            // ??????
            wv.loadUrl(url);
          } else {
            mEditText.setText("????????");
          }
        } catch (Exception e) {
          Log.e(TAG, e.toString());
        }
      }
    });
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && (wv.canGoBack())) {
      // ??????????
      wv.goBack();
      return true;
    }
    return super.onKeyDown(keyCode, event);
  }

  Handler handler = new Handler() {
    public void handleMessage(Message msg) {
      Bundle bundle = msg.getData();
      wv.loadUrl("javascript:setDate('" + bundle.getString("dateString")
          + "','" + bundle.getString("eleId") + "');");
      // wv.loadUrl("javascript:setDate('2011-11-11','123');");????????????????????
    };

  };

  // targetSdkVersion>=17???????@JavascriptInterface???????Uncaught TypeError:
  // Object [object Object] has no method
  // 'toString'?????4.2?????????target=android-17???
  // ???target??17???????????JavascriptInterface? ?????jar??????????js?????
  // ?????Uncaught TypeError: Object [object Object] has no method 'toString'
  // ????????targetSdkVersion??17???????@JavascriptInterface???????????target>=17??jar?????
  // ???????17????????????????????????
  // ????????targetSdkVersion<17?????????target>=17,jar?????????????????target<17,?????????
  class MyJavaScriptInterface {
    @JavascriptInterface
    public void chooseDate(String date, final String eleId) {
      String[] dateParts = date.split("-");
      new DatePickerDialog(
          MainActivity.this,
          new OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year,
                int monthOfYear, int dayOfMonth) {
              // Toast.makeText(MainActivity.this,
              // year + "-" + monthOfYear + "-" + dayOfMonth, 0)
              // .show();
              String dateString = year
                  + "-"
                  + ((monthOfYear + 1) < 10 ? "0"
                      + (monthOfYear + 1)
                      : (monthOfYear + 1))
                  + "-"
                  + (dayOfMonth < 10 ? "0" + dayOfMonth
                      : dayOfMonth);
              // ????????UI????
              // wv.loadUrl("javascript:setDate(" + dateString +
              // "," + eleId
              // + ")");
              Message msg = new Message();

              Bundle bundle = new Bundle();
              bundle.putString("dateString", dateString);
              bundle.putString("eleId", eleId);

              msg.setData(bundle);
              handler.sendMessage(msg);

            }
          }, Integer.parseInt(dateParts[0]),
          Integer.parseInt(dateParts[1]) - 1, Integer
              .parseInt(dateParts[2])).show();

    }
  }
}




Java Source Code List

wjj.js.MainActivity.java
wjj.js.MyWebChromeClient2.java
wjj.js.MyWebChromeClient.java