PhoneGAP中我无法找到网络访问相关的API。我不知道该如何通过PhoneGAP访问网络。从PhoneGAP API中唯一看到和网络有关的只有一个检查当前网络状态的API。
那就编写java代码来自己提供接口啊,编写一个phonegap插件,将它注册到xml/plugins.xml里面,具体参照这个里面的注册方式,其中
[code="java"][/code]这是一个插件的注册
下面是插件代码
[code="java"]package com.pingan.market.plugin;
import java.io.File;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;
public class PinganGapPlugin extends Plugin {
public static final String ACTION = "list";
@Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
Log.d("DirectoryListPlugin", "Plugin Called");
PluginResult result = null;
if (ACTION.equals(action)) {
try {
String fileName = data.getString(0);
JSONObject fileInfo = getDirectoryListing(new File(fileName));
Log
.d("DirectoryListPlugin", "Returning "
+ fileInfo.toString());
result = new PluginResult(Status.OK, fileInfo);
} catch (JSONException jsonEx) {
Log.d("DirectoryListPlugin", "Got JSON Exception "
+ jsonEx.getMessage());
result = new PluginResult(Status.JSON_EXCEPTION);
}
} else {
result = new PluginResult(Status.INVALID_ACTION);
Log.d("DirectoryListPlugin", "Invalid action : " + action + " passed");
}
return result;
}
private JSONObject getDirectoryListing(File file) throws JSONException {
JSONObject fileInfo = new JSONObject();
fileInfo.put("filename", file.getName());
fileInfo.put("isdir", file.isDirectory());
if (file.isDirectory()) {
JSONArray children = new JSONArray();
fileInfo.put("children", children);
if (null != file.listFiles()) {
for (File child : file.listFiles()) {
children.put(getDirectoryListing(child));
}
}
}
return fileInfo;
}
}[/code]
在phonegap.js中
使用PhoneGap.addPlugin函数对接口进行注册 其中name是DirectoryListPlugin,也就是xml里面的name属性,其它的你参照phonegap.js中它的插件注册方式就可以。
你想使用什么API访问网络呢?
在phonegap中可以使用ajax访问网络,可以使用websocket访问网络。
不好意思,好久没有上外网了。
其实只是为了访问网络不需要这么麻烦:
直接在[b]loadUrl[/b]方法中传入http://www.baidu.com这样就可以了,但是页面中有的url你会发现它会去使用默认浏览器打开,不用担心,可以通过res/xml/phonegap.xml进行配置
内容如下:
[code="java"]
<?xml version="1.0" encoding="utf-8"?>
<!-- Load PhoneGap configuration from res/xml/phonegap.xml.
Approved list of URLs that can be loaded into PingAnGap -->
<!-- Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) -->
[/code]
这段代码的配置指定了日志级别,一共分5个,还有就是默认使用该phonegap访问的url,这个url是一个正则表达式,你可以任意配置。