2012-06-05 103 views
1

我正在嘗試的是我得到我的當前位置(座標),我想發佈這些座標在服務器上。我用WAMP製作了一臺服務器。我已經在java中編寫了php代碼和代碼,但是它顯示我在POST單詞中出現錯誤。請告訴我,如果它的正確或如果我可以修改它!從Android手機發布在PHP服務器上的GPS座標

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); 

?>

EDITED 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; 
} 

} 
+1

您可以修改它。 – shadyyx

+0

您是否收到任何錯誤? – shadyyx

+0

獲取單詞POST的錯誤... –

回答

2

我可以看到這裏的主要問題是,你是在談論POST但你android LocationService您正在創建一個HttpGet對象CT:

HttpGet httppost = new HttpGet("http://.../serverFile.php"); 

,然後從無處一個httpost變量用作post

post.setHeader("json",json.toString()); 
post.getParams().setParameter("jsonpost",postjson); 

在PHP我不知道什麼是你想實現這個:

$_SERVER['HTTP_JSON']; 

因爲我確定沒有這樣的索引。相反,調用

$_GET['jsonpost']; // <-- that is the parameter name from Your JAVA code... 

像複製+粘貼類似的問題,這裏的代碼它看起來幾乎(此人應該是重複!):Sending Data From Android To Server with JSON data

編輯:好吧,讓我們假設你的android JAVA代碼是好的,你通過GET發送數據。那麼你將要修你的PHP - 試試這個:

<?php 
echo 'Hello, world!'; 

$json = $_GET['jsonpost']; // get the json you sent through GET... 
$data = json_decode($json); // decode the json formatted string... 

print_r($data); // print out the $data variable to see whether everything is OK... 

$devid = $data->devid; 
$longitude = $data->longitude; 
$latitude = $data->latitude; 

$con = mysql_connect("","","") or die('Could not connect: ' . mysql_error());  
mysql_select_db("a5234826_ul", $con); 

echo "devid" +$devid; 
echo "latitude" + $latitude; 
echo "longitude" + $longitude; 

$sql = "INSERT INTO `a5234826_ul`.`locations` (
    `devid`, 
    `latitude`, 
    `longitude` 
) VALUES (
    '$Devid', 
    '$latitude', 
    '$longitude' 
);"; 
if (!mysql_query($sql,$con)) { 
    die('Error: ' . mysql_error()); 
} 

mysql_close($con); 
echo json_encode($variable); 

你應該與print_r($data);出發,看看數據是否到達和JSON是否被解碼,並且還看什麼性質包含。

編輯2由於發佈logcat:您是否從logcat讀取錯誤?這是如此清楚!程序員當然應該明白錯誤信息是什麼意思,應該關於他在做什麼,而不是從某處複製粘貼代碼而不考慮它。在您的manifest.xml中您需要添加一個許可READ_PHONE_STATE - 閱讀有關這裏的權限:http://developer.android.com/reference/android/Manifest.permission.html並在此處添加對manifest.xml的權限:http://developer.android.com/guide/topics/security/security.html#permissions

+0

沒有複製粘貼它從那裏..我應該怎麼做..你能幫我在那...請。 –

+0

嘿,我編輯了一些東西...萬物工作正常...但座標和設備ID沒有被張貼... –

+0

好,然後嘗試谷歌這個詞:android post data [直接鏈接](https:// www .google.cz /#q =機器人+交+數據&FP = 1)。首先使用谷歌,當沒有解決方案時,然後在這裏問這裏... – shadyyx

相關問題