2011-09-20 5 views
2

위치가 변경 될 때마다 백그라운드 서비스가 서버에 조정 된 현재 GPS를 보내도록합니다.Android에서 서버로 조정 된 GPS 보내기

공공 무효 ONSTART (의도 의도 INT의에서 StartId) {

Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); 
    Log.d(TAG, "onStart"); 

    // Acquire a reference to the system Location Manager 
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 

    // Define a listener that responds to location updates 
    LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location loc) { 
      loc.getLatitude(); 

      loc.getLongitude(); 

      double lat = loc.getLatitude(); 
      double lon = loc.getLongitude(); 


      String curr_lat = Double.toString(lat); 
      String curr_lon = Double.toString(lon); 

      postData(curr_lat,curr_lon); 

      String Text = "My current location is: " + 

      "Latitud = " + loc.getLatitude() + 

      "Longitud = " + loc.getLongitude(); 

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


     } 

문제는 postData를이 때 위치 변경 호출되지 않습니다 그 방법이다 : 지금이 코드를 가지고있다. postData는 HTTP를 사용하여 서버에 조정 된 현재 GPS를 보냅니다.

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를 locationManager에 등록하지 마십시오. 하나의 양식을 사용해야합니다. requestLocationUpdates

서비스의 onStop에서 청취자와 함께 removeUpdates에 전화하는 것을 잊지 마십시오.

0

위치 업데이트를 요청하기 시작한 곳이 어디에도 없습니다.

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

그냥 팁 : 당신은 당신이 다음과 같은 호출하고 확인할 수있는 새로운 위치가 이전보다 더 나은 경우 위치에게이 변화 할 때마다 게시하기보다는, 만 게시 할 수 있습니다. Check this page은 한 위치가 다른 위치보다 나은지 판단하는 방법입니다.

관련 문제