📱 Android WebView
Display Web Pages as a part of your Activity Layout.
What is Android WebView ?
WebView is an Android provided View like TextView,EditText,Button etc. using this WebView we can load HTML pages as a part of your activity layout and it uses Webkit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more. by default WebView does not enable JavaScript so we can manually enable it by using WebSettings and can bind JavaScript code to client side android code.it’s easier to build WebView in your android application rather than performing a network request and then parsing the respond data and rendering it an android layout.if you want full fledged web browser then you probably want to invoke the browser application with a URL intent rather than show it with a WebView.
Uri uri = Uri.parse("https://www.developer.android.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);In this post we will understand and work with the basic things and handling methods of Android WebView.
To get Internet access, request the INTERNET permission in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>Adding a WebView to Your Application
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView" />Using JavaScript in WebView
If the web page you want to load in your WebView is using JavaScript you must enable JavaScript for your WebView using WebSettings with getSettings() method then enable JavaScript with setJavaScriptEnabled() method.
webView.getSettings().setJavaScriptEnabled(true);WebSettings : provides access to a variety of other settings for the WebView like user agent,zoom control,file access,database settings etc.
setJavaScriptEnabled : to enable javascript execution.
Binding JavaScript code to Android code
If the loaded web page events that can communicate to the android client. for example your web page’s button clicking event can call the method in your android code to displays the toast notification to the user by creating interface between your JavaScript code and client side android code.
Get Ramkumar N’s stories in your inbox
Join Medium for free to get updates from this writer.
To bind a new interface between your JavaScript and Android code, call addJavascriptInterface(), passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.
private class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void showToast(String toast) {
final String string = toast;
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, string, Toast.LENGTH_SHORT).show();
}
});
}
}add addJavaScriptInterface.
webView.addJavascriptInterface(new WebAppInterface(this),"android");sample.html
<!DOCTYPE html>
<html>
<body>
<h2>Sample HTML Page</h2>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
android.showToast(toast);
}
</script>
</body>
</html>addJavascriptInterface (Object object,String name)
this method allows JavaScript to access the java object’s method by injecting interface object using the supplied name. JavaScript interacts with java object on a private, background thread of this WebView so thread safety is an important task here.
Note : you must add the @JavaScriptInterface annotation if you set your targetedSdkVersion is 17 or higher.The object that is bound to your JavaScript runs in another thread and not in the thread in which it was constructed.
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, string, Toast.LENGTH_SHORT).show();
}
});here i am using Handler this allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue
Caution : this produce a dangerous security issue because when the loaded HTML is untrustworthy this will mislead the application depends on attacker’s choice.
Handling Page Navigation
If you click the link in the web page by default it will launch the web browser and loads the appropriate URL. so we have to create a client for override this behavior to load the clicked link within your WebView and also can be navigate backward and forward through the web page history that’s maintain by your WebView. android provides 2 client systems they are,
WebViewClient using setWebViewClient()
If you won’t require too many features, rendering HTML is enough you can use WebViewClient.
WebChromeClient using setWebChromeClient()
If you want to handle javascript dialogs,favicons,titles and progress you should use WebChromeClient.
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webView.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressDialog.dismiss();
}
});the following are the some override methods of WebViewClient
shouldOverrideUrlLoading (WebView view,String url)
This method returns false when the current WebView handles the requested URL so no need to override the URLloading else the host application handles the URLusing Intent.
onPageStarted (WebView view,String url,Bitmap favicon)
This method notify the host application that a page has started loading.
onPageFinished (WebView view,String url)
This method notify the host application that a page has finished loading.
Navigating Web Page History
WebView automatically stores the history of visited web pages so we can navigate backward and forward through the history with goBack() and goForward() methods.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}goBack() goes back in the history of this WebView.
goForward() goes forward in the history of this WebView.
canGoBack() returns true if the web page history for the user to visit.
canGoForward() check whether there is a forward history.
Hope you have enjoyed this post,Feel free to comment below for doubts or chat with me in Facebook or drop me E-mail for replies. Share is care.










