ste*_*ong 3 javascript android cordova
我有和应用程序构建PhoneGap,我正在尝试与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");
}
Run Code Online (Sandbox Code Playgroud)
javascript接口:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在Javacript位于外部文件(I创建,其具有在此行的HTML文件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 to work.
}
Run Code Online (Sandbox Code Playgroud)
我在其他帖子中读到可以在PhoneGap和Android之间进行通信,但是因此我没有取得任何成功.我确实设法创建一个警报,但那是loadUrl("javascript:alert('Alert');"),但我也读过你不应该这样做,因为这sendJavascript()是为了什么(它会导致泄漏,重新加载页面等).我试图通过这种sendJavascript()方法拍摄几个字符串,但无济于事:
sendJavascript("javascript:alert('Alert');")sendJavascript("javascript:sendToInterface();")sendJavascript("sendToInterface();")sendJavascript("window.sendToInterface();")如何从本地通信 - > PhoneGap(或我已经有什么错误)?因此,其他帖子和问题并没有帮助我解决这个特殊问题.
读:
编辑
我写了一个工作项目:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
cordova.xml
<?xml version="1.0" encoding="utf-8"?>
<cordova>
<access origin=".*"/> <!-- allow local pages -->
<log level="DEBUG"/>
<preference name="classicRender" value="true" />
</cordova>
Run Code Online (Sandbox Code Playgroud)
Index.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>
Run Code Online (Sandbox Code Playgroud)
其中一个问题是javascript是在一个单独的文件中(我认为这是其中一个问题).如果不是要问太多,我怎样才能正确地调用java,并用什么值?如何实现execute方法以及如何调用它(我在JQuery中真的很糟糕)?
首先,您正在使用Plugin子类.Plugin已被弃用并已被替换CordovaPlugin.如果您使用旧版本的PhoneGap,我建议您升级.
其次,你的执行电话是错误的.插件开发的文档明确指出你必须传递5个参数,而你传递3个空值.您如何期待处理?
cordova.exec(function(winParam) {}, function(error) {}, "service",
"action", ["firstArgument", "secondArgument", 42,
false]);
Run Code Online (Sandbox Code Playgroud)
在这里,service,action和参数数组确定在Java代码中会发生什么.前两个决定了在某些条件下JavaScript会发生什么.因此,虽然您可以为前两个使用null,但您必须指定最后三个.
我有一个适用于PhoneGap 2.3.0的工作示例插件.请参阅以下代码:
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) + " was 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 + " and the Activity knows it!");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,您可以使用Java端插件来处理两个自定义"操作" - buttonClicked和animationRunning.这些行为符合我的目的,但你可以用其他名称命名.
现在,您仍然需要注册您的插件,以便Cordova了解它.这是在xml/config.xml文件中完成的.在plugins,您必须添加以下内容:
<plugin name="ExampleJSCommunicator" value="com.example.phonegap.ExampleJSCommunicator"/>
Run Code Online (Sandbox Code Playgroud)
然后,您可以从JavaScript传递数据(或"操作"),如下所示.注意参数(which.id并animationRunning在数组中传递):
cordova.exec (null, null, "ExampleJSCommunicator", "buttonClicked", [which.id]); // my first action
cordova.exec (null, null, "ExampleJSCommunicator", "animationRunning", [animationRunning]); // my second action
Run Code Online (Sandbox Code Playgroud)
这两个exec调用将触发类中的execute方法ExampleJSCommunicator,并将在相应的if块中处理.只要在包含cordova.js文件后声明JavaScript代码,调用exec的位置无关紧要.我的JavaScript包含在一个单独的main.js文件中,它可以正常工作:
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="main.js"></script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18097 次 |
| 最近记录: |