简体   繁体   English

PHP服务器从android应用程序接收数据

[英]PHP server to receive data from android application

I am new to the communication side. 我是沟通方面的新手。 Was just trying to get some data from an android application periodically. 只是试图定期从Android应用程序获取一些数据。 But somehow its not working.. Have written a php script Do i need to add something more..? 但不知何故它不工作..已经写了一个PHP脚本我需要添加更多的东西..? Do i need to add any permission in androidmanifest..? 我是否需要在androidmanifest中添加任何权限..? Also giving my android app code.. It force closes when I click get my location. 还给我的Android应用程序代码..当我点击获取我的位置时它强制关闭。

PHP script PHP脚本

<?php
echo 'Hello, world!';
$json = $_GET['jsonpost'];//get the post you sent...
$data = json_decode($json); //decode the json formatted string...
print_r($data);
$id = $data->id;
$devid = $data->devid;
$latitude = $data->latitude;
$longitude = $data->longitude;
$service = $data->service;
$con = mysql_connect("","","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("a5234826_ul", $con);
$devid = $_POST['devid']; 
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
echo "devid" +$devid;
echo "latitude" + $latitude;
echo "longitude" + $longitude; 
$sql = "INSERT INTO  `a5234826_ul`.`locations` (
`id` ,
`devid` ,
`latitude` ,
`longitude` ,
`service`
)
VALUES (
NULL ,  '$devid',  '$latitude',  '$longitude', '$service'  
)";
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
mysql_close($con);
echo json_encode($variable);

?>

LocationService.java LocationService.java

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

public int onStartCommand(Intent intent, int flags, int startId) {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
wl.acquire();
context = this;
final String who = intent.getStringExtra("who");
final LocationManager locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationListener listener = new LocationListener(){

    // start location changed

    public void onLocationChanged(Location loc) {
        double latitude = loc.getLatitude();
        double longitude = loc.getLongitude();


        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://.../serverFile.php");
        JSONObject json = new JSONObject();


        TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        String devid = telephonyManager.getDeviceId();

        String postData = "{\"request\":{\"type\":\"locationinfo\"},\"userinfo\":{\"latitude\":\""+latitude+"\",\"longitude\":\""+longitude+"\",\"devid\":\""+devid+"\"}}";




        try {  

            json.put("longitude", longitude);//place each of the strings as you did in postData method
            json.put("latitude", latitude);

            json.put("devid", devid);

            JSONArray postjson=new JSONArray();
            postjson.put(json);
            httppost.setHeader("json",json.toString());
            httppost.getParams().setParameter("jsonpost",postjson);     
            HttpResponse response = httpclient.execute(httppost);

            // for JSON retrieval:
            if(response != null)
            { 
            InputStream is = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
            }
            } catch (IOException e) {
            e.printStackTrace();
            } finally {
            try {
            is.close();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }
            String jsonStr = sb.toString(); //take the string you built place in a string



            JSONObject rec = new JSONObject(jsonStr);
            String longitudecord = rec.getString("lon");
                String latitudecord = rec.getString("lat");
            // ...
            }
            }catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
                } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }




        if (who.equals("me")){
            Intent i = new Intent(context.getPackageName()+".LocationReceived");
            i.putExtra("lat", String.valueOf(latitude));
            i.putExtra("longitude", String.valueOf(longitude));
            i.putExtra("accuracy", String.valueOf(loc.getAccuracy()));
            context.sendBroadcast(i);
            Notification notif = new Notification();
            NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            notif.tickerText = "Location Found!";
            notif.icon = R.drawable.ic_launcher;
            notif.flags = Notification.FLAG_AUTO_CANCEL;
            notif.when = System.currentTimeMillis();
            Intent notificationIntent = new Intent(context, TestLocatorActivity.class);
            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            notificationIntent.putExtra("lat", String.valueOf(latitude));
            notificationIntent.putExtra("longitude", String.valueOf(longitude));
            notificationIntent.putExtra("accuracy", String.valueOf(loc.getAccuracy()));
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
            notif.setLatestEventInfo(context, "Location Found!", "Click to open.", contentIntent);
            nm.notify(0, notif);
        } else {
            SmsManager smsMan = SmsManager.getDefault();
            smsMan.sendTextMessage(who, null, "http://maps.google.com/maps?q=loc:"+latitude+","+longitude, null, null);
            smsMan.sendTextMessage(who, null, "Latitude: "+latitude+"\nLongitude: "+longitude, null, null);
        }
        locMan.removeUpdates(this);
        try {
            wl.release();
        } catch (Exception e){
            e.printStackTrace();
        }
        stopSelf();
    }

    public void onProviderDisabled(String provider){


    }

    public void onProviderEnabled(String provider) {
        //Log.i(tag, "GPS IS ON");
    }

    public void onStatusChanged(String provider, int status, Bundle extras){
        switch(status) {
            case LocationProvider.OUT_OF_SERVICE:
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
            case LocationProvider.AVAILABLE:
                break;
        }
    } };


locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);

return 2;
}

}

One more thing I am trying to get the value of the latitude and longitude fron LocationService class to Post class is the code in Post class right.. Please help me.. 还有一件事我试图将纬度和经度的值从LocationService类传递到Post类是Post类中的代码吧..请帮帮我..

Like @Vivek Kumar Srivastava said. 就像@Vivek Kumar Srivastava所说的那样。

When you use postData your sending it in Json format so on your php end you need to actually decode it... 当你使用postData以json格式发送它时所以在你的php端你需要实际解码它...

the code would be like this. 代码就是这样的。

it maybe better to create a JSON object in your android code like this... 最好在你的android代码中创建一个JSON对象,就像这样......

As Vivek Kumar Srivastava said: 正如Vivek Kumar Srivastava所说:

When you use postData your sending it in Json format so on your php end you need to actually decode it. 当你使用postData以json格式发送它时所以在你的php端你需要实际解码它。

It may be better to create a JSON object in your android code like below. 在你的Android代码中创建一个JSON对象可能更好,如下所示。

private postData() throws JSONException{  
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://.../serverFile.php");
JSONObject json = new JSONObject();

try {           
    json.put("longitude", longitude);//place each of the strings as you did in postData method
    json.put("latitude", latitude);
    json.put("service", service);
    json.put("devid", devid);

    JSONArray postjson=new JSONArray();
    postjson.put(json);
    post.setHeader("json",json.toString());
    post.getParams().setParameter("jsonpost",postjson);     
    HttpResponse response = httpclient.execute(httppost);

    // for JSON retrieval:
    if(response != null)
    { 
    InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
    while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
    }
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    is.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    String jsonStr = sb.toString(); //take the string you built place in a string



    JSONObject rec = new JSONObject(jsonStr);
    String longitudecord = rec.getString("lon");
        String latitudecord = rec.getString("lat");
    // ...
    }
    }catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
        }
    }

Now your php code... 现在你的PHP代码......

$json = $_SERVER['HTTP_JSON'];//get the post you sent...
$data = json_decode($json); //decode the json formatted string...
$longitude = $data->longitude;
$latitude = $data->latitude;
$service = $data->service;
$devid = $data->devid;

And then continue with your sql from there on. You will encode them into JSON if you want to read them back into Android as shown in the code above... 如果你想将它们读回到Android中,你会将它们编码为JSON,如上面的代码所示......

You have a problem in your php code because in Android side data send as a json format like 您的PHP代码有问题,因为在Android端数据发送为像json格式

 String postData = "{\"request\":{\"type\":\"locationinfo\"},\"userinfo\":{\"latitude\":\""+latitude+"\",\"longitude\":\""+longitude+"\",\"deviceid\":\""+deviceid+"\"}}"

but you directly try to fetch data without decoding json. 但你直接尝试获取数据而不解码json。

So need to first decode your json then fetch the data in specific order 因此需要首先解码您的json,然后按特定顺序获取数据

see the below link for more details 有关详细信息,请参阅以下链接

http://php.net/manual/en/function.json-decode.php http://php.net/manual/en/function.json-decode.php

I suggest you make a simple script to ensure that you are indeed properly accessing the db. 我建议你制作一个简单的脚本,以确保你确实正确访问数据库。 You could just run the script in a browser and that way rule out any connection/access issues to the db: 您可以在浏览器中运行该脚本,这样可以排除对db的任何连接/访问问题:

<?php
mysql_connect("localhost","user","pass");
mysql_select_db("dbName");
$sql=mysql_query("select * from TABLENAME where COLUMNNAME like 'searchparameter'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

I don't see any PHP code to accept POST data. 我没有看到任何PHP代码接受POST数据。 I have written similar apps where I send data to the server and record it to the database. 我编写了类似的应用程序,我将数据发送到服务器并将其记录到数据库中。 I usually have some script where I accept the POST data and use the values from that. 我通常有一些脚本,我接受POST数据并使用其中的值。 You must use the POST method in Android SDK to send the data to the URL. 您必须使用Android SDK中的POST方法将数据发送到URL。 This is easier than sending the data using JSON and then decoding it on the PHP end. 这比使用JSON发送数据然后在PHP端解码更容易。 If I needs to receive data from the server I return values as JSON and then decode it in Android using the SDK. 如果我需要从服务器接收数据,我将值返回为JSON ,然后使用SDK在Android中对其进行解码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM