MainActivity.java 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package com.itant.androidjs;
  2. import android.content.Context;
  3. import android.os.Handler;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.webkit.JavascriptInterface;
  8. import android.webkit.JsResult;
  9. import android.webkit.WebChromeClient;
  10. import android.webkit.WebView;
  11. import android.webkit.WebViewClient;
  12. import android.widget.Button;
  13. import android.widget.Toast;
  14. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  15. private Button btn_java_invoke_js;
  16. private WebView web_view;
  17. @Override
  18. protected void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.activity_main);
  21. btn_java_invoke_js = (Button) findViewById(R.id.btn_java_invoke_js);
  22. btn_java_invoke_js.setOnClickListener(this);
  23. web_view = (WebView) findViewById(R.id.web_view);
  24. web_view.loadUrl("file:///android_asset/web.html");
  25. web_view.getSettings().setJavaScriptEnabled(true);
  26. // 支持alert
  27. web_view.setWebChromeClient(new WebChromeClient() {
  28. @Override
  29. public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
  30. return super.onJsAlert(view, url, message, result);
  31. }
  32. });
  33. web_view.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app");
  34. }
  35. @Override
  36. public void onClick(View v) {
  37. switch (v.getId()) {
  38. case R.id.btn_java_invoke_js:
  39. // Java调用JS
  40. new Handler().post(new Runnable() {
  41. @Override
  42. public void run() {
  43. web_view.loadUrl("javascript:javaInvokeJs()");
  44. }
  45. });
  46. break;
  47. }
  48. }
  49. /*
  50. * JavaScript Interface. Web code can access methods in here
  51. * (as long as they have the @JavascriptInterface annotation)
  52. */
  53. public class WebViewJavaScriptInterface{
  54. private Context context;
  55. /*
  56. * Need a reference to the context in order to sent a post message
  57. */
  58. public WebViewJavaScriptInterface(Context context){
  59. this.context = context;
  60. }
  61. /*
  62. * This method can be called from Android. @JavascriptInterface
  63. * required after SDK version 17.
  64. */
  65. @JavascriptInterface
  66. public void makeToast(String message, boolean lengthLong){
  67. Toast.makeText(context, message, (lengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT)).show();
  68. }
  69. }
  70. }