Android Comunicazione da Javascript a Java (Android)

Esempio

Attività Android

package com.example.myapp;

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

public class WebViewActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        WebView webView = new WebView(this);
        setContentView(webView);

       /* 
        *   Note the label Android, this is used in the Javascript side of things
        *   You can of course change this.
        */
        webView.addJavascriptInterface(new JavascriptHandler(), "Android");
    
        webView.loadUrl("http://example.com");
    }
}

Java Javascript Handler

import android.webkit.JavascriptInterface;

public class JavascriptHandler {

    /**
     *  Key point here is the annotation @JavascriptInterface
     *
     */
    @JavascriptInterface
    public void jsCallback() {
       // Do something
    }

    @JavascriptInterface
    public void jsCallbackTwo(String dummyData) {
       // Do something
    }
}

Pagina Web, chiamata Javascript

<script>
... 
Android.jsCallback();
...
Android.jsCallback('hello test');
...
</script>

Suggerimento extra

Passando in una struttura dati complessa, una possibile soluzione è usare JSON.

Android.jsCallback('{ "fake-var" : "fake-value", "fake-array" : [0,1,2] }');

Sul lato Android usa il tuo parser JSON preferito, ovvero: JSONObject