PhoneGap与Android之间通信实现原理是本我要介绍的内容,主要来了解PhoneGap实现原理。PhoneGap为移动开发者带来了全新的开发模式,使用javascript调用移动设备的本地接口,这样,你就可以在js中调用你手机的摄像头,文件系统等等功能,理论上来说,你的本地应用程序可以访问的接口都可以通过javascript来调用了。不得不说,这样功能实在是很强大。既能使用javascript,html等web技术来实现程序,又能通过统一的接口来调用本地接口。兼具了web应用与app应用的特点。
那么PhoneGap是如何实现javascript脚本调用本地设备的接口的呢?
相信大家都很想知道吧,那我就少点废话了,一句话,通过ajax发送请求,实现脚本对设备发送消息;设备接受到消息处理后通过webView的loadUrl方法(这是Android系统下的浏览器控件对象)执行脚本实现脚本的回调。
主要的代码有下面三处:
1、
xmlhttp.open("GET", "http://127.0.0.1:"+PhoneGap.JSCallbackPort+"/"+PhoneGap.JSCallbackToken , true);
- 1.
这是phonegap.js里面的代码,通过ajax请求,发送消息给设备。
2、
active = true;
ServerSocket waitSocket = new ServerSocket(0);
port = waitSocket.getLocalPort();
token = UUID.randomUUID().toString();
while(active)
{
Socket connection = waitSocket.accept();
BufferedReader xhrReader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 40);
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
String request = xhrReader.readLine();
String response = "";
if(active && request != null)
{
if(request.contains("GET"))
{
String requestParts[] = request.split(" ");
if(requestParts.length == 3 && requestParts[1].substring(1).equals(token))
{
synchronized(this)
{
do
{
if(!empty)
break;
try
{
wait(10000L);
break;
}
catch(Exception e) { }
} while(true);
}
if(active)
{
if(empty)
{
response = "HTTP/1.1 404 NO DATA\r\n\r\n ";
} else
{
response = "HTTP/1.1 200 OK\r\n\r\n";
String js = getJavascript();
if(js != null)
response = (new StringBuilder()).append(response).append(URLEncoder.encode(js, "UTF-8")).toString();
}
} else
{
response = "HTTP/1.1 503 Service Unavailable\r\n\r\n ";
}
} else
{
response = "HTTP/1.1 403 Forbidden\r\n\r\n ";
}
} else
{
response = "HTTP/1.1 400 Bad Request\r\n\r\n ";
}
output.writeBytes(response);
output.flush();
}
output.close();
xhrReader.close();
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
这是java代码,监听javascript代码发送过来的请求
3、
appView.loadUrl("javascript:PhoneGap....");
- 1.
通过loadUrl来执行javascript代码。
小结:PhoneGap与Android之间通信实现原理的内容介绍完了,希望通过本文的学习能对你有所帮助!