Javascript calls from Android using PhoneGap -
i have , application built phonegap
, , i'm trying communicate javascript
native code.
in droidgap
extending class:
@override public void oncreate(bundle savedinstancestate) { logger.log("oncreate"); super.oncreate(savedinstancestate); super.init(); super.appview.getsettings().setjavascriptenabled(true); super.appview.getsettings().setsupportzoom(true); super.appview.getsettings().setbuiltinzoomcontrols(true); super.appview.getsettings().setdisplayzoomcontrols(false); jsinterface = new communicationinterface(this, appview); super.appview.addjavascriptinterface(jsinterface, "communicationinterface"); }
the javascriptinterface:
public class communicationinterface { private webview mappview; private droidgap mgap; public communicationinterface(droidgap gap, webview view) { mappview = view; mgap = gap; } public string getteststring() { return "teststring"; } public void parse(object o) { logger.log(o); } }
the javacript
located in external file (i create html file has line in header
: <script type="text/javascript" src="scripts.js"></script>
)
scripts.js
:
function sendtointerface() { alert("alert"); var map = new object(); (...) window.communicationinterface.parse(map); //communication js -> android seems work. }
i read in other posts it's possible communicate between phonegap , android, thusfar i've not had success. did manage create alert, loadurl("javascript:alert('alert');")
, i've read shouldn't because that's sendjavascript()
(and causes leaks, reloads page, etc). i've tried shoot couple of strings through sendjavascript()
method, no avail:
sendjavascript("javascript:alert('alert');")
sendjavascript("javascript:sendtointerface();")
sendjavascript("sendtointerface();")
sendjavascript("window.sendtointerface();")
how communicate native -> phonegap (or what's wrong have)? thusfar other posts , questions haven't helped me particular problem.
read:
- http://www.jumpbyte.com/2012/phonegap-native-to-javascript/
- phonegap: "processmessage failed" unable send javascript function (cordova 2.5.0)
- communication between android java , phonegap javascript? (although other direction, i'm trying both)
- http://www.intelligrape.com/blog/2013/01/31/using-sendjavscript-to-inject-javascript-into-android-phonegap-application/
- phonegap - android - calling javascript native causes leakedwindow
- how call javascript function android using phonegap plugin
edit
i wrote working project:
java part
import org.apache.cordova.droidgap; import org.json.jsonexception; import org.json.jsonobject; import android.os.bundle; import android.util.log; public class app extends droidgap { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); super.loadurl("file:///sdcard/ds/index.html"); system.out.println("loading sdcard"); thread t = new thread() { public void run() { try { (int = 0; < 3; i++) { sleep(2000); sendvalue("value " + i, "another vlaue " + i); } } catch (exception e) { e.printstacktrace(); } }; }; t.start(); } public void sendvalue(string value1, string value2) { system.out.println("sendvalue in app"); jsonobject data = new jsonobject(); try { data.put("value1", value1); data.put("value2", value2); } catch (jsonexception e) { log.e("commtest", e.getmessage()); } string js = string.format("window.plugins.appcomm.updatevalues('%s');", data.tostring()); this.sendjavascript(js); } } import org.apache.cordova.api.plugin; import org.apache.cordova.api.pluginresult; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject; import android.util.log; public class appcomm extends plugin{ private static appcomm instance; public appcomm () { instance = this; } public static appcomm getinstance() { return instance; } @override public pluginresult execute(string action, jsonarray args, string callbackid) { system.out.println("in execute appcomm"); return null; } public void sendvalue(string value1, string value2) { system.out.println("sendvalue in appcomm"); jsonobject data = new jsonobject(); try { data.put("value1", value1); data.put("value2", value2); } catch (jsonexception e) { log.e("commtest", e.getmessage()); } string js = string.format( "window.plugins.commtest.updatevalues('%s');", data.tostring()); this.sendjavascript(js); } }
res/xml/plugins.xml
<plugins> <plugin name="app" value="org.apache.cordova.app"/> <plugin name="geolocation" value="org.apache.cordova.geobroker"/> <plugin name="device" value="org.apache.cordova.device"/> <plugin name="accelerometer" value="org.apache.cordova.accellistener"/> <plugin name="compass" value="org.apache.cordova.compasslistener"/> <plugin name="media" value="org.apache.cordova.audiohandler"/> <plugin name="camera" value="org.apache.cordova.cameralauncher"/> <plugin name="contacts" value="org.apache.cordova.contactmanager"/> <plugin name="file" value="org.apache.cordova.fileutils"/> <plugin name="networkstatus" value="org.apache.cordova.networkmanager"/> <plugin name="notification" value="org.apache.cordova.notification"/> <plugin name="storage" value="org.apache.cordova.storage"/> <plugin name="temperature" value="org.apache.cordova.templistener"/> <plugin name="filetransfer" value="org.apache.cordova.filetransfer"/> <plugin name="capture" value="org.apache.cordova.capture"/> <plugin name="battery" value="org.apache.cordova.batterylistener"/> <plugin name="splashscreen" value="org.apache.cordova.splashscreen"/> <plugin name="appcomm" value="com.example.plugin.appcomm"/> </plugins>
cordova.xml
<?xml version="1.0" encoding="utf-8"?> <cordova> <access origin=".*"/> <!-- allow local pages --> <log level="debug"/> <preference name="classicrender" value="true" /> </cordova>
index.html header
<head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0" /> <title> </title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.css" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> </script> <script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"> </script> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> var appcomm=function(){}; appcomm.prototype.updatevalues=function(a){ var map = new object(); map["x1"] = "hallo"; map["x2"] = "hi"; cordova.exec(null, null, null); }; cordova.addconstructor(function(){cordova.addplugin("appcomm",new appcomm)}); </script> </head>
one of problems javascript in separate file (i think 1 of problems). if isn't ask, how can call java back, , values? how implement execute method , how call (i'm bad @ jquery)?
firstly, using plugin
subclass. plugin
has been deprecated , has been replaced cordovaplugin
. if you're using old version of phonegap, recommend upgrade.
secondly, exec call wrong. docs plugin development state have pass 5 parameters, while you're passing 3 nulls. how expect handled?
cordova.exec(function(winparam) {}, function(error) {}, "service", "action", ["firstargument", "secondargument", 42, false]);
here, service
, action
, array of parameters determine happen in java code. first 2 determine happen in javascript under conditions. so, while can use null first two, have specify last three.
i have working example plugin works phonegap 2.3.0. see code below:
public class examplejscommunicator extends cordovaplugin { public boolean execute (final string action, final jsonarray args, callbackcontext callbackcontext) throws jsonexception { pluginresult.status status = pluginresult.status.ok; string result = ""; cordova.getactivity ().runonuithread (new runnable () { @override public void run() { try { string displaytext = ""; if (action.equals ("buttonclicked")) { displaytext = args.getstring(0) + " clicked"; } else if (action.equals ("animationrunning")) { displaytext = args.getboolean(0) ? "animation started running" : "animation stopped running"; } textview label = (textview) cordova.getactivity().findviewbyid (r.id.textview); label.settext (displaytext + " , activity knows it!"); } catch (jsonexception e) { e.printstacktrace(); } } }); return true; } }
with code above, have java-side plugin capable of handling 2 custom "actions" - buttonclicked
, animationrunning
. these actions serve purposes, name them otherwise.
now, still need register plugin, cordova know it. done in xml/config.xml
file. under plugins
, have add following:
<plugin name="examplejscommunicator" value="com.example.phonegap.examplejscommunicator"/>
then can pass data (or "actions") javascript follows. note parameters (which.id
, animationrunning
passed in array):
cordova.exec (null, null, "examplejscommunicator", "buttonclicked", [which.id]); // first action cordova.exec (null, null, "examplejscommunicator", "animationrunning", [animationrunning]); // second action
these 2 exec
calls trigger execute method in examplejscommunicator
class , handled in respective if blocks. doesn't matter call exec, long declare javascript code after include cordova.js file. javascript contained within separate main.js file , works fine:
<script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8" src="main.js"></script>
Comments
Post a Comment