Sometimes it is required to show useful information to the user in android App and in that case,WebView is very useful.But to access WebView,we need to develop a two-way connection between application and WebView.
Here I will show you the best way to develop the connection using Javascript.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/click_me" />
</LinearLayout>
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/container" />
</RelativeLayout>
MainActivity.java
-
Firstly onCreate method of class
webView = (WebView) findViewById(R.id.webView);
button = (Button) findViewById(R.id.button);
webView.getSettings().setJavaScriptEnabled(true);
// Add the custom WebViewClient class
webView.setWebViewClient(new CustomWebViewClient());
// Add the javascript interface
webView.addJavascriptInterface(new JavaScriptInterface(), "interface");
// Load the example html file to the WebView
webView.loadUrl("file:///android_asset/index.html");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("javascript:(function() { callFromApp();})()");
}
});
-
CustomWebViewClient method:
private class CustomWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// If the url to be loaded starts with the custom protocol, skip
// loading and do something else
if (url.startsWith("myApp://")) {
Toast.makeText(MainActivity.this, "Yipee..", Toast.LENGTH_LONG).show();
return true;
}
return false;
}
}
3.JavaScript Interface method:
private class JavaScriptInterface {
@JavascriptInterface
public void callFromJS() {
Toast.makeText(MainActivity.this, "JavaScript interface call", Toast.LENGTH_LONG).show();
}
}
Make asset folder in application and put html file in it and name it as index.html.Now the two way connection is ready and on button click ,you can check for the result u want.
Note-The name of your file u put in asset folder should have the same name which u used while loading url in webView.
That's all there.Hope it helps
0 Comment(s)