我有和使用PhoneGap
構建的應用程序,並且我試圖從本機代碼與Javascript
進行通信。使用PhoneGap從Android進行Javascript調用
DroidGap
擴展類
:
@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");
}
的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);
}
}
的Javacript
位於外部文件(我創造出具有在header
這一行的HTML文件:<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 to work.
}
我在其他文章中看到它可以在PhoneGap和Android之間進行通信,但是因此我沒有取得任何成功。我確實設法創建了一個提醒,但那是loadUrl("javascript:alert('Alert');")
,但我也讀過,你不應該這樣做,因爲這就是sendJavascript()
的原因(它會導致泄漏,重新加載頁面等)。我試圖通過sendJavascript()
的方法來拍了幾個字符串,但無濟於事:
sendJavascript("javascript:alert('Alert');")
sendJavascript("javascript:sendToInterface();")
sendJavascript("sendToInterface();")
sendJavascript("window.sendToInterface();")
如何從本地通信 - > PhoneGap(或者我已經有什麼問題)?因此,其他職位和問題沒有幫助我解決這個問題。
閱讀:
- http://www.jumpbyte.com/2012/phonegap-native-to-javascript/
- Phonegap: "processMessage failed" unable to send javascript function (Cordova 2.5.0)
- Communication between Android Java and Phonegap Javascript?(雖然這是另一個方向,但我想兩者都做)
- http://www.intelligrape.com/blog/2013/01/31/using-sendjavscript-to-inject-javascript-into-android-phonegap-application/
- Phonegap - Android - Calling javascript from native causes leakedwindow
- how to call javascript function from android using phonegap plugin
編輯
我寫了一個工作項目:
的Java部分
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 from sdcard");
Thread t = new Thread() {
public void run() {
try {
for (int i = 0; i < 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 from 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>
索引。html標頭
<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>
其中一個問題是,JavaScript是在一個單獨的文件(我認爲這是其中一個問題)。如果問題不多,我該如何正確地調用java回來,並用什麼值呢?如何實現execute方法以及如何調用它(我在JQuery中真的很糟糕)?
你使用哪個版本的PhoneGap? – Shade 2013-04-10 12:49:57
@Shade我正在使用科爾多瓦2.5.0 – stealthjong 2013-04-10 13:06:08