2012-04-25 170 views
3

接收數據,我是新來的交際面。只是試圖從android應用程序定期獲取一些數據。但不知何故,它不工作..已經寫了一個PHP腳本我需要添加更多的東西..? 我是否需要在androidmanifest中添加任何權限..? 也給我的android應用代碼..它強制關閉時,我點擊獲取我的位置。PHP服務器從Android應用程序

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

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

} 

還有一兩件事我想獲得的緯度和經度弗朗LocationService類Post類的值是郵政代碼一流的權利.. 請幫助我..

+0

您是否通過瀏覽器發送測試表單數據以查看錯誤是否由PHP輸出? – 2012-04-25 02:36:05

+0

否..但是代碼完整的PHP服務器接收數據..? – 2012-04-25 02:38:05

+0

它看起來像你有所有必要的部分給我。 – 2012-04-25 02:38:56

回答

1

我建議你製作一個簡單的腳本來確保你確實正確地訪問了數據庫。你可以只運行在瀏覽器腳本,這種方式排除任何連接/訪問問題的分貝:

<?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(); 
?> 
1

你在你的PHP代碼有問題因爲在Android端數據發送爲json格式,如

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

但您直接嘗試獲取數據而不解碼json。

所以需要以特定的順序首先解碼的JSON,然後獲取數據

看到下面的鏈接查看更多細節

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

+0

你能幫我解碼嗎? – 2012-04-25 10:26:50

+0

我其實並沒有太多的理解..你能幫我解決... – 2012-04-25 10:47:26

+0

是你通過給定的鏈接 – 2012-05-03 05:08:10

3

像@Vivek庫馬爾塔瓦說。

當您使用POSTDATA您發送它以JSON格式等你的PHP你到底需要實際解碼它...

代碼會是這樣。

它也許更符合這樣的Android代碼創建一個JSON對象...

正如Vivek Kumar Srivastava說:

當您使用POSTDATA您發送它以JSON格式等等,你需要你的php結束實際解碼它。

這可能是更好的在你的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 
     } 
    } 

現在你的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. 您將編碼成JSON,如果你想閱讀它們放回Android作爲顯示在上面的代碼...

+0

通過你好,謝謝你的迴應..所以我只需要在我的代碼中添加此..?你給的PHP部分和Java部分Post.java ..? – 2012-05-07 13:59:17

+0

我只是通過你的個人資料..你想要做的是發佈經緯度和長期從你的應用程序發佈到PHP的網站..你能幫我嗎?請 – 2012-05-10 08:35:58

+0

是的。你有沒有嘗試使用我上面提出的建議? – inspired 2012-05-11 09:41:51

0

我看不出有任何PHP代碼接受POST數據。我寫了類似的應用程序,將數據發送到服務器並將其記錄到數據庫。我通常有一些腳本,我接受POST數據並使用它的值。您必須使用Android SDK中的POST方法將數據發送到URL。這比使用JSON發送數據然後在PHP端進行解碼要容易。如果我需要從服務器接收數據,我將返回值爲JSON,然後使用SDK在Android中對其進行解碼。

相關問題