2011-09-20 28 views
2

我希望我的後臺服務能夠在位置發生變化時將當前的GPS協調發送到服務器。現在我有這樣的代碼:從Android協調發送GPS到服務器

公共無效在onStart(意向意圖,詮釋startid){

​​

的問題是方法POSTDATA不會被調用時的位置變化。 postData發送當前GPS協調到服務器使用HTTP

public void postData(String currLat, String currLon) { 
    // List with arameters and their values 

    String Text2 = "String is: " + 

    "Latitud = " + currLat + 

    "Longitud = " + currLon; 

    Toast.makeText(getApplicationContext(), Text2, Toast.LENGTH_LONG).show(); 

    HttpPost post = new HttpPost("http://www.url.com/*.php"); 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("myusername", currLat)); 
    nameValuePairs.add(new BasicNameValuePair("mypassword", currLon)); 
    HttpClient client = new DefaultHttpClient();  

    try { 
     post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = client.execute(post); 
     HttpEntity entity = response.getEntity(); 
     String responseText = EntityUtils.toString(entity); 
     responseText = responseText.trim(); 

    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    } 

什麼是不調用函數postData?即使它並沒有一次稱呼它。

+1

是否'postData'永遠不會被調用或者是整個'onLocationChanged'永遠不會被調用? – Otra

+1

另外請注意,onLocationChanged可以被調用很多次。如果你在onLocationChanged中設置了一個調試點,你會發現它可以每秒調用一次,甚至可以在一秒鐘內調用多次。您可能需要設置最短時間來更新。 – Jack

回答

2

您從不向locationManager註冊您的locationListener。您應該使用一種形式的requestLocationUpdates

不要忘記在您的服務的onStop中與您的聽衆聯繫撥打removeUpdates

0

我沒有看到您開始請求位置更新的任何地方。你能確認你調用以下:

locationManager.requestLocationUpdates(provider, 0, 0, this); 
0

只是一個提示:每次改變時間,而不是發佈位置,只有在新的位置比前一個更好的張貼。 Check this page以確定一個位置是否比另一個更好。