It's actually quite simple. Give this a try:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;
public class CustomActivity extends Activity {
private Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView view=(WebView)findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("file:///android_asset/index.html");
view.addJavascriptInterface(new JavaScriptBridge(), "Android");
}
final class JavaScriptBridge
{
public void ProcessJavaScript(final String scriptname, final String args)
{
mHandler.post(new Runnable()
{
public void run()
{
String url="file:///android_asset/img.jpg";
webview.loadUrl("javascript:image(\""+url+"\")");
}
});
}
}
}
index.html:
<script type="text/javascript">
function getimage()
{
Android.ProcessJavaScript("image",null);
}
function image(src) {
var img = document.createElement("IMG");
img.src = src;
document.getElementById('image').appendChild(img);
}
</script>
and include the following,
<body onload="getimage()" >
To add more images:
function image(src) {
//var img = document.createElement("IMG");
//img.src = src;
// document.getElementById('image').appendChild(img);
images = eval('(' + src+ ')');
for (i = 0; i < images.length; i++) {
var img = document.createElement("IMG");
img.src = images[i];
document.getElementById('image').appendChild(img);
}
}
and pass a String array instead of a String in the load url like
final class JavaScriptBridge
{
public void ProcessJavaScript(final String scriptname, final String args)
{
mHandler.post(new Runnable()
{
public void run()
{
//String url="file:///android_asset/img.jpg";
//webview.loadUrl("javascript:image(\""+url+"\")");
ArrayList<String> url=new ArrayList<String>();
url.add("file:///android_asset/img1.jpg");
url.add("file:///android_asset/img2.jpg");
url.add("file:///android_asset/img3.jpg");
webview.loadUrl("javascript:image(\""+url+"\")");
}
});
}
}
To execute the image script multiple times:
final class JavaScriptBridge
{
public void ProcessJavaScript(final String scriptname, final String args)
{
mHandler.post(new Runnable()
{
public void run()
{
// You can load the URL at any point in the application. See below to call it from within another function.
callFirstTime(scriptname,args);
// Check below to load URL in another class Test.java
Test newtest=new Test();
newtest.methodToLoadUrl(scriptname,args);
}
});
}
}
public void callFirstTime(String script, String arguments)
{
// Add images with a String array and pass it here
webview.loadUrl("javascript:image(\""+url+"\")");
}