Python handler
Code
How it works
General
The UI Handler will be listening (waiting) for an event that will be posted by the Javascript side. This event will include data which is a JSON encoded dict. The handler will then dispatch to the function corresponding to the "task" key in the data dict. Once the task has done its job, the handler will post a response event which will be caught by the Javascript side.Init and dispatch
The UIHandler class is actually never used directly. Each script needs to extend it into another class (e.g. class CallUIHandler(UIHandler)) and then loop on the wait function. The dispatch dict of the UIHandler is empty, meaning that any call to a given task will lead nowhere. The dispatch dict of the extended class (CallUIHandler) must "point" from a task string (e.g. "callme") to a function of the CallUIHandler (e.g. dispatch = {"callme":self.callme}). The callme method is then defined in the CallUIHandler (e.g. def callme( self, data ): ).Receiving event and responding
While looping on the wait() function, the handler is waiting for an event (by default "python"). Data from the event is directly decoded from JSON into a python dict so the data is available to each of the task functions. The task function must return the data it wishes to pass back to the javascript side - that data will be JSON encoded before passing it to the response event, which means that it should be an dict/list/tuple (otherwise JSON encoding might fail).Miscellaneous stuff
There are a startLoad(title,message) and a stopLoad() functions available, that are simple ways of showing/hiding an Android spinner dialog.There is a default log function that may be overridden in the extended class.
The 0.2 second thing, is due to a glitch in the droid.waitForEvent function: If Python catches an event and posts its response too quickly, the Javascript side will miss it. So we make sure that our processing takes at least 0.2 seconds. (value was found by trial and error)
You did a great job. Thumbs up! (>^_^)>
ReplyDelete(im gonna bookmark this on my phone =} )
This is the best SL4A info I've found anywhere - good job!
ReplyDeleteGREAT JOB! Really nice! But I got to ask. How did you close the webview? I saw that you're looking for a workarround. Me too. Did you got it?
ReplyDelete