Why does OnLocationChanged called twice every second?

601 Views Asked by At

I have an Android Application that write one line in a file every time the method OnLocationChanged() is called. Data inside each line is separated by a semicolon. I store the epoch time (System.currentTimeMillis()), the latitude and the longitude of the new location:

File example 1:

1477294804758;45.17358813287331;5.750043562562213 1477294805758;45.17358813287331;5.750043562562213

Between those two lines, there is 1 second gap so everything is fine.

Most of the time, it works. But sometimes, every second, it writes two lines :

File example 2:

1477294806761;45.17358813287331;5.750043562562213 1477294806776;45.17358813287331;5.750043562562213 1477294807767;45.17358813287331;5.750043562562213 1477294807779;45.17358813287331;5.750043562562213

OnLocationChanged is called twice every second with a 15 millis gap.

I could not find a way to reproduce this bug. It is erratic.

Here is how I implement the location provider :

locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);  
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,MainActivity.this);

My MainActivity implements LocationListener.

Here is how I write data to the file :

    @Override
    public void onLocationChanged(Location location) {

        try {
            File dataFile = new File(saveFileFlyData);
            if(!dataFile.exists())
                dataFile.createNewFile();

            FileOutputStream fOut = null;
            try {
                fOut = new FileOutputStream(dataFile, true);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            try {

                if(mCurrentLocation != null)
                {
                    osw.write(System.currentTimeMillis() +
                            ";" + mCurrentLocation.getLatitude() +
                            ";" + mCurrentLocation.getLongitude()+
                            "\n"
                    );
                }
                else
                {
                    osw.write(0 +
                            ";" + 0 +
                            ";" + 0+
                            "\n"
                    );
                }

                osw.flush();
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        }
    }

I cant see why it works from time to time.

0

There are 0 best solutions below