Issue
I have added a Javascript interface object to a WebView using the addJavascriptInterface()
method and I am trying to invoke a method on that object using WebView.loadUrl()
.
The object is a simple class called JSInterface
. It has a single method called echo()
that takes no parameters and returns void. The URL I am passing to loadUrl()
is "javascript:JSInterface.echo()"
(JSInterface is also the interface name I used for addJavascriptInterface()
).
When I run the attached app, the echo()
method never executes. There are no errors in the logcat or anywhere else. What do I need to do to invoke echo()
from Javascript?
This is the activity with all source.
It is of course right after I post the question that I figure out what's wrong. In the attached code I am calling addJavascriptInterface()
from a thread other than the UI thread. Moving addJavascriptInterface()
to onCreate()
fixes the problem.
package test.pg;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
public class TestActivity2
extends Activity
{
WebView webview;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/www/invoke.html");
TimerThread t = new TimerThread(webview);
t.start();
}
class TimerThread
extends Thread
{
long lastRun;
WebView appView;
public TimerThread(WebView appView)
{
lastRun = System.currentTimeMillis();
this.appView = appView;
}
public void run()
{
try
{
while (true)
{
if (System.currentTimeMillis() - lastRun < 5000)
{
Thread.sleep(5000);
}
else
{
appView.addJavascriptInterface(new JSInterface(), "JSInterface");
InvokerThread t = new InvokerThread(appView);
t.start();
lastRun = System.currentTimeMillis();
}
}
}
catch (Exception e)
{
Log.e("InvokerThread", "exception=" + e.toString(), e);
}
}
}
class InvokerThread
extends Thread
{
WebView appView;
public InvokerThread(WebView appView)
{
this.appView = appView;
}
public void run()
{
String function = "javascript:JSInterface.echo()";
appView.loadUrl(function);
}
}
class JSInterface
{
public void echo()
{
System.out.println("JSInterface.echo()");
Log.i("JSInterface", "JSInterface.echo()");
}
}
}
Solution
It is of course right after I post the question that I figure out what's wrong. In the attached code I am calling addJavascriptInterface() from a thread other than the UI thread. Moving addJavascriptInterface() to onCreate() fixes the problem.
Answered By - Mirza Dobric
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.