DEV Community

Sadhan Sarker
Sadhan Sarker

Posted on

Android Native & JavaScript Binding

Now a day we all know about hybrid application development. It really becomes popular it gives us power like Native Implementation without sacrificing lots. As a web & android developer, we have to need combining our android and web application together. Android & iOS gives use those types of access through WebKit.

As a developer, we need to convert our website into a mobile app then the challenge comes. To render any website we use WebView in android and turn a website into a mobile app. But when we need performance and hardware native support we need more, rather than simply webview implementations. Also, we want to need custom control through native logic.

So, today's talk I'm going to demonstrate, how we can take some custom control into web pages through WebKit interfacing.

Let's deep drive into implementations. Create an empty Android Project and follow the below instructions,

πŸ”°Open MainActivity.java file and includes

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    WebView webView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webView);



        webView.getSettings().setJavaScriptEnabled(true);       // must enable javascript
        webView.setWebViewClient(new WebViewClient());          // must add web client

        // Binding
        webView.addJavascriptInterface(
                new CommonInterface(getApplicationContext()), "Android"
        );


        String folderPath = "file:android_asset";    // Get the Android assets folder path
        String fileName = "/sample.html";            // Get the HTML file name
        String file = folderPath + fileName;         // Get the exact file location
        webView.loadUrl(file);                       // load file or https://mesadhan.github.io
    }
}

Enter fullscreen mode Exit fullscreen mode

πŸ”° Create CommonInterface.java file and includes

import android.content.Context;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

/** Accessible from the web page */

public class CommonInterface {
    Context context;

    CommonInterface(Context c) {
        context = c;
    }

    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public String getMessage() {
        return "Hello From Android Native!";
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ”° Open activity_main.xml file and includes

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Enter fullscreen mode Exit fullscreen mode

Finally, we need a web page which actually plays the main role here

πŸ”° Create a file in /assets/sample.html and includes

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
    <title>Sample Web Page</title>
    <style type="text/css">
        div {
            background-color:#FFCC99
        }
        h1, h3 {
            color:red;
            text-align: center;
        }
        .item {
            width: 100%;
            height: 50px;
            text-align: center;
            font-size: 20px;
        }
    </style>
</head>
<body>
<br><br>
<h1>Android WebView</h1>
<h3 id="welcome"></h3>
<input  class="item" type="text" placeholder="Enter Name" id="nameField"/>
<br><br>
<button  class="item" onClick="showAndroidToast()">Show Android Toast</button>
<br><br>
<button  class="item" onClick="setMessageFromHtml('Hello, From HTML')">Set Message From Html</button>
<br><br>
<button class="item" onClick="getMessageFromAndroid()">Get Message From Android</button>

<script type="text/javascript">
    function showAndroidToast() {
        let nameField = document.getElementById('nameField').value;
        Android.showToast(nameField);
    }
    function setMessageFromHtml(param) {
       document.getElementById('welcome').innerHTML = param;
    }
    function getMessageFromAndroid() {
       document.getElementById('welcome').innerHTML = Android.getMessage();
    }
</script>
</body>
Enter fullscreen mode Exit fullscreen mode

Alt Text


πŸ‘Œ Congratulations!. & Thank You!
Feel free to comments, If you have any issues & queries.

References:

Top comments (3)

Collapse
 
fultonbrowne profile image
Fulton Browne

This is really neat, some one could legit stream android apps.

Collapse
 
mesadhan profile image
Sadhan Sarker

Thanks, @FultonB for sharing your opinion.!

Collapse
 
engmms profile image
engmms

Good demonstrate