将GPS坐标从Android发送到服务器

时间:2011-09-20 14:53:33

标签: android http gps coordinates

我希望我的后台服务能够在位置发生变化时将当前GPS协调发送到服务器。现在我有这个代码:

public void onStart(Intent intent,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?即使它没有一次调用它。

3 个答案:

答案 0 :(得分:2)

您永远不会使用locationManager注册locationListener。您应该使用requestLocationUpdates

的一种形式

不要忘记在您服务的onStop上与您的听众联系removeUpdates

答案 1 :(得分:0)

我没有看到您开始请求位置更新的任何地方。你能否证实你在打电话给以下人员:

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

答案 2 :(得分:0)

只是提示:不是每次更改时发布位置,只有在新位置优于前一位置时才发布。 Check this page用于确定某个位置是否优于其他位置的方法。