Javascript Interface for Android and Javascript communication
The following is an example of two way communication between Android code and Javascript in a WebView.
Enable internet permission and register the WebViewActivity class
The layout for the WebViewActivity class
The WebAppInterface.java for communcating between Android and javascript.
import android.content.Context; import android.os.Build; import android.webkit.JavascriptInterface; import android.widget.Toast; public class WebAppInterface { Context mContext; // Instantiate the interface and set the context WebAppInterface(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 int getAndroidVersion() { return android.os.Build.VERSION.SDK_INT; } @JavascriptInterface public void showAndroidVersion(String versionName) { Toast.makeText(mContext, versionName, Toast.LENGTH_SHORT).show(); } }
The WebView class WebViewActivity.java
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class WebViewActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_webview); WebView webView = (WebView) findViewById(R.id.webview); webView.loadUrl("file:///android_asset/index.html"); webView.addJavascriptInterface(new WebAppInterface(this), "AndroidInterface"); // To call methods in Android from using js in the html, AndroidInterface.showToast, AndroidInterface.getAndroidVersion etc WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.setWebViewClient(new MyWebViewClient()); webView.setWebChromeClient(new MyWebChromeClient()); } private class MyWebViewClient extends WebViewClient { @Override public void onPageFinished (WebView view, String url) { //Calling a javascript function in html page view.loadUrl("javascript:alert(showVersion('called by Android'))"); } } private class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d("LogTag", message); result.confirm(); return true; } } }
The html file in assets folder, index.html
Hello
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts