我正在创建一个位置应用程序,用户可以从服务器中调整某些功能,所以我希望服务器开始与用户的电话进行通信。 但首先,我想从php开启与android的通信。
有没有办法从php服务器与Android手机通信?
我已经使用从HTTP到服务器的通信返回JSONObject
,但我无法找到任何用于android的php调用。
我认为它与使您的手机响铃的应用程序完全相同。
答案 0 :(得分:1)
您需要让Android客户端连接到您的服务器并传递您的JSON消息。如果客户端需要从服务器获取一些数据并断开连接,那么您可以使用普通的HTTP类型GET。
但是,如果你决定需要一个长期运行的TCP连接双向传递JSON,那么你应该考虑像WebSockets这样的东西。我写了Android WebSocket demo。默认情况下,Android客户端连接到websocket.org echo服务器,但可以轻松更改。
我还找到了PHP WebSockets implementation。
现在,如果您的计划是将消息从服务器推送到客户端而客户端没有启动连接,那么您将需要GCM(Google云消息传递)之类的东西。这是一篇涵盖GCM and PHP的文章。
答案 1 :(得分:1)
查看Google Cloud Messaging for Android。
适用于Android的Google Cloud Messaging(GCM)是一项服务,可让您将数据从服务器发送到用户的Android设备。这可能是一个轻量级消息,告诉您的应用程序有从服务器获取的新数据(例如,朋友上传的电影),或者它可能是包含高达4kb有效负载数据的消息(因此即时消息等应用程序可以直接使用消息)。
答案 2 :(得分:0)
通常,从服务器端到客户端创建连接很复杂,因为:
使用网络: 这取决于浏览器如何支持JavaScript API,尤其是新的HTML5功能,例如Server Sent Events
使服务器能够通过HTTP或使用将数据推送到网页 专用的服务器推送协议,本规范介绍了 EventSource接口。
答案 3 :(得分:0)
请使用php在mysql中使用以下链接获取商店数据,你需要创建webservice,因为你将从php服务器获得两个响应
1)Json
2)xml
如果您显示示例请访问以下链接 Creating a basic web services in php
还可访问此链接以获得更好的说明 http://phpmaster.com/lets-talk-1/
答案 4 :(得分:0)
您可以使用HTTpReq类:
public class HttpReq {
public String send (String url){
//send a http request and get the result
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
}
然后你使用这个类来建立连接并调用你的php文件来获取数据作为JSonObject。
ht = new HttpReq();
// send a http request with GET
x=ht.send("http://10.0.2.2/myFolder/myFile.php");
JSONArray jArray;
JSONObject json_data;
String h[]=x.split("<");
try {
jArray = new JSONArray(h[0]);
json_data = jArray.getJSONObject(0);
url=json_data.getString("url");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在您的Php文件中,您可以使用此方法获取JSon数据或将其发送到Android应用程序
Json_decode($string);
和
Json_encode($string);
我希望这会对你有所帮助:)。