Zeeshan
Zeeshan

Reputation: 1655

requestLocationUpdates called many time when location changes actually incremented one time

I am sending latitude, longitude and location Name for saving on server.... the problem is when I run my app first time its ok and save above data one time... when I close my app and emulator is running and eclipse also and start my app again then it save above data 2 times..... similarly it incremented by 1 when I close and start again my app... I don't know why it calls requestLocationUpdates() many times... without sending to server it works fine.. any idea about this please help me...

sending data to server.. this function is implemented in send.java class

public String postData(List<? extends NameValuePair> nameValuePairs, String wurl){

     // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(wurl); 
    try {

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        InputStream is = response.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(20);
        int current = 0;
        while((current = bis.read()) != -1){
            baf.append((byte)current);
        } 
        /* Convert the Bytes read to a String. */
        text = new String(baf.toByteArray());

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    return text;

}

onlocationchaned function is in location.java class that implements LocationListener and calling above function inside onlocationchanged

public void onLocationChanged(android.location.Location loc) {

    String response;
    latitude = loc.getLatitude();
    longitude = loc.getLongitude();

    // Changing type double to string for sending 
    lati = Double.toString(latitude);
    logi = Double.toString(longitude);

        String Text = "My current location is: " + 
                  " Latitude = " + Location.lati + 
                  " Longitude = "+ Location.logi;
        Toast.makeText(c,  Text , Toast.LENGTH_LONG).show();
        Log.d("lat", "Changed");

        locationName = getAddress(latitude, longitude);

        // Add location related data
        List<BasicNameValuePair> locationNameValuePair = new ArrayList<BasicNameValuePair>(4);
        locationNameValuePair.add(new BasicNameValuePair("latitude", lati));
        locationNameValuePair.add(new BasicNameValuePair("longitude", logi));
        locationNameValuePair.add(new BasicNameValuePair("locName", locationName));

        response = con.postData(locationNameValuePair, wurl);
        Toast.makeText(c, response, Toast.LENGTH_LONG).show();

        Log.v("IGA", "Address " + locationName);
        Toast.makeText(c, locationName, Toast.LENGTH_LONG).show();
}


 public String getAddress(double lat, double lng) {
    Geocoder geocoder = new Geocoder(c, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
        Address obj = addresses.get(0);
        //String add = obj.getAddressLine(0);
        String add = obj.getThoroughfare();
        add = add + ", " + obj.getSubLocality();
        add = add + ", " + obj.getLocality();
        add = add + ", " + obj.getCountryName();

         return add;

    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
    } catch (IndexOutOfBoundsException e) {
        e.printStackTrace();
        Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
    }
    return "";
}

and locationManager in mainavtivity that extends MapActivity

   protected void onCreate(Bundle savedInstanceState) {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MapView view = (MapView) findViewById(R.id.themap);
        view.setBuiltInZoomControls(true);


        LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location mylocation = new Location(MainActivity.this);
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mylocation);


    }

Upvotes: 1

Views: 2404

Answers (1)

Haris ur Rehman
Haris ur Rehman

Reputation: 2663

mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mylocation);

should be the following if you want to assure 1000ms have elapsed and the client has moved 5 meters between location updates

LocationListener customLocationListener = new CustomLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5, customLocationListener);

Also, in your activity onPause() method call

mlocManager .removeUpdates(customLocationListener);

You have to implement CustomLocationListener like below:

private class CustomeLocationListener implements LocationListener
{
    @Override
    public void onLocationChanged(Location loc)
    {
        // when location changes, add the record in the database, send to server etc...
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();
    }

    @Override
    public void onProviderDisabled(String provider)
    {}

    @Override
    public void onProviderEnabled(String provider)
    {}

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras)
    {}
}

Upvotes: 1

Related Questions