Sunday, December 30, 2012

JavaScript example in Android

This is very helpful example for JavaScript

Please check
1. https://github.com/scottagarman/Android-JavaScript-Interface-Example
2. http://blog.objectgraph.com/index.php/2012/03/16/android-development-javascript-bridge-example-fully-explained/

SOURCE CODE


package ranjit.jsinandroid;
public class JSAndroid extends Activity {
private WebView wv;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsandroid);

// create interface
JsInterface jsInterface = new JsInterface();

// get webview and enable js
wv = (WebView) findViewById(R.id.web_view);
wv.getSettings().setJavaScriptEnabled(true);

// add interface
wv.addJavascriptInterface(jsInterface, "android");// android is the
// keyword that will
// be exposed in js

// load file
wv.loadUrl("file:///android_asset/test.html");
}

// javascript interface
private class JsInterface {
// function that will be called from assets/test.js
// js example: android.log('my message');
public void log(String msg) {
Log.d("MSG FROM JAVASCRIPT", msg);
Toast.makeText(getApplicationContext(), "JavaScript working...", 1)
.show();
}
}
}

---------------------
XML file


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/web_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

------------------
HTML file
Save test.html file in assets folder


<html> <head> </head> <body> <a href="javascript:void(0);" onclick="android.log('omg its working!');">Click on this link for a log message</a> </body> </html>


No comments:

Post a Comment