Last Updated: November 21, 2017
·
11.57K
· xandout

Javascript to Java Bridge

This is an example to show how you can call Java code from an HTML and JavaScript UI using Android's WebView.

The Inspiration

Google Docs

The Code

The first step is to configure your main activity.

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainAct extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        //Default
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Setting the stage
        WebView myWebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = myWebView.getSettings();
        //Enable JS in WV.  This opens some real security risks(Cross-Origin Resource Sharing/XSS)
        webSettings.setJavaScriptEnabled(true);
        myWebView.setWebViewClient(new WebViewClient());
        //Inject Java class into myWebView's JS
        myWebView.addJavascriptInterface(new JSInterface(this), "Android"); //You will access this via Android.method(args);
        //Load the UI
        myWebView.loadUrl("file:///android_asset/www/index.html");
    }
}

Here we have a WebView that will cover the entire visible area of the application.

I have commented the above code to help clarify things that are not obvious.

This next part will actually implement a few methods to call from our client side JS later.
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.widget.Toast;

/**
 * Created by Mitchell on 6/16/2014.
 */
public class JSInterface {
    Context mContext;
    JSInterface(Context c){
        mContext = c;
    }

    public void showToast(String message){
        Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
    }


    public void SavePreferences(String key, String value){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }
    public String LoadPreferences(String key){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        return sharedPreferences.getString(key, "");
    }

    public void Vibrate(long milliseconds){
        Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(milliseconds);
    }

    public void SendSMS(String phoneNumber, String message){
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber,null, message,null,null);
    }


}

So with minimal code so far we have made it possible to store user preferences in a Key:Value system, display a Toast, vibrate the phone and send an SMS(not-MMS or multipart here).

The last part we need to do is the UI, the following is the bare minimum required (I am not proud of this)...

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head lang="en">
    <meta charset="UTF-8">
    <title></title>

</head>
<body>


<input id="user" type="text" placeholder="Username" name="user">
<input id="pass" type="password" placeholder="Password" name="pass">
<input type="button" value="Save" onClick="savePrefs()" />
<input type="button" value="Load" onClick="loadPrefs()" />

<input type="button" value="Toast" onClick="showAndroidToast('Hello from JavaScript!!!')">
<input type="button" value="Vibrate" onClick="vibrate(500)">

<br>
<br>
<br>
<br>
<input id="phoneNumber" type="number" placeholder="Phone Number" name="phoneNumber">
<input id="message" type="text" placeholder="Message (160 Characters)" maxlength="160" name="message">
<input type="button" value="SendSMS" onClick="sendSMS(document.getElementById('phoneNumber').value, document.getElementById('message').value)">
<script type="text/javascript">

    //These are some basic functions to demonstrate the ease of calling Java methods from JS
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }

    function savePrefs(){
        Android.SavePreferences("user", document.getElementById('user').value);
        Android.SavePreferences("pass", document.getElementById('pass').value);
    }

    function loadPrefs(){
        var user = Android.LoadPreferences("user");
        var pass = Android.LoadPreferences("pass");

        showAndroidToast("Username: " + user + "\nPassword: " + pass);


    }

    function vibrate(milliseconds){
        Android.Vibrate(milliseconds);
    }

    function sendSMS(phoneNumber, message){

        Android.SendSMS(phoneNumber, message);
    }
</script>

</body>
</html>

The Result

Hopefully this is helpful, you can find the full code over at GitHub

1 Response
Add your response

Hi I tried this code inside fragment child and doesn't seem to work can you please help

over 1 year ago ·