为了了解JS与Android之间是如何通信的,所以简单的撸了如下代码:
使用Android Studio初始化一个项目,项目主要文件如下
MainActivity.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package com.example.aurora.myapplication;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import android.webkit.JavascriptInterface; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
final WebView webView = (WebView) findViewById(R.id.webview);
Button button = (Button) findViewById(R.id.callJs); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { webView.loadUrl(("javascript: callJs('Hello JS')")); } });
webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(new WebChromeClient(){ @Override public boolean onJsAlert(WebView view, String url, String message,final JsResult result){ return super.onJsAlert(view,url,message,result); } });
class JsObject { @JavascriptInterface public void sayHello(String msg) { Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } } webView.addJavascriptInterface(new JsObject(), "example"); webView.loadUrl("file:///android_asset/example.html"); } }
|