Monday, December 28, 2009

Yes, you can run JavaScript inside a Service

Contrary to what I heard from the android-developers group, you can actually create a WebView inside an Android Service, and use it to run JavaScript. JavaScript is needed by NubiNews in processing the HTML data downloaded from the news web sites.

This means, finally, I can implement offline syncing inside a Service. It will probably take a month from this point ....

In my test, this code is added to a Service's onCreate function:

Object o = new Object() {
public void trace(String s) {
System.out.println("JavaScript: " + s);
}
};

public void onCreate() {
WebView webView = new WebView(this);
WebSettings webSettings = webView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
webView.addJavascriptInterface(o, "backdoor");

webView.loadData("<" + "script language="\">window.backdoor.trace('I AM HERE');<" + "/script>", "text/html", "utf-8");

and, I see this "proof of life" output from logcat:

I/System.out(10440): JavaScript: I AM HERE

1 comment:

  1. hi,

    maybe the sdk changed a lot since your post, but now, it seems that the webview behaves differently.

    My tests were the following:
    1- webview in an activity, instanciated but not binded to the screen:
    - webpage loaded
    - its resources loaded
    - its javascript executed and we can interact with it

    2- webview in a service
    - webpage loaded
    - its resources not loaded
    - its javascript not executed and we can not interact with it

    I haven't test your code, but i think it does not longer work under android 2.3

    Let us know if you know a workaround

    cheers

    ReplyDelete