Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send events from python to javascript using sl4a

I wanted to know the answer to a simple question but i have'nt found a good one (i've google it for hours :) )

I'm playing with the sl4a with python and i can send events from js to the python script, but the js is not catching the eventPost i put in the code below from python to js.

Anyone knows how is this been done or if there is another way without the registerCallback?

HTML CODE :

<html>
<head>
<script>
var droid = new Android();
function doit(){
    droid.makeToast("Text send :=>"+document.getElementById("msg").value);
    droid.eventPost("doit",document.getElementById("msg").value);
}

function alert_me(data){
    droid.makeToast("All done!");
    document.getElementById("msg").value = '';
}

droid.registerCallback("done",alert_me);
</script>
</head>
<body>
<input type="text" name="boton" id="msg" value="" />
<input type="button" name="boton" value="Go!" onclick="javascript:doit()" />
</body>
</html>

PYTHON CODE:

import android,time

if __name__ == '__main__' :

    droid = android.Android()
    droid.webViewShow("file:///sdcard/sl4a/scripts/sample.html")

    while True:        
        event = droid.eventWait().result
        if event["name"] == 'doit':
          droid.makeToast("Event catched! %s" % event['data'])

          droid.eventPost("done","Done message")
          time.sleep(2)


    droid.exit()
like image 864
Tony Avatar asked Aug 22 '11 23:08

Tony


1 Answers

This is simple to get working, but isn't obvious or well documented.

First you want to get a hook to the Android object inside the webview. Then you can use it to register one or more callbacks. For a simple example, we'll just do one that pops an alert with a message from Python.

    var droid = new Android();

    droid.registerCallback("echo", function(msg) {
        alert(msg.data)
    });

In this case, echo is the name of the event type you want this callback to handle. So this will handle 'echo events'. The event names are arbitrary strings, just call them whatever makes sense.

In the Python script that launched the webview, you can now post events to the registered handler whenever you like.

droid.eventPost("echo", "hello world")

The second argument here is the message you want to pass to the JavaScript callback.

Note that although you pass the message back as a string, it arrives in the JavaScript function as an object. That object, we're calling it msg above, has an attribute called data which contains the string you passed from the Python side.

like image 165
Carl Smith Avatar answered Oct 02 '22 15:10

Carl Smith