title: Cyclically get the GPS data
body: <p>I am implementing the android app which uses GPS data (especially GPS time). Now I am using interface "LocationListner" in "GPSReader" class and it seems like to "listen" to the GPS data only when the coordination changes.</p>
  
  <p>I am also trying to store the GPS data in global variable "gpsTime" in public class "Common" and use it from "SensorReader" class. In this class, I tried to get the GPS data cyclically such as 100 Hz, however, as I mentioned before, the data such as latitude, longitude and GPS time sometimes doesn't change because there is no change of coordination. I want to use GPS time as reference time, so want to get it cyclically such as 100 Hz. I think "LocationListner" is "passive", so is there any "positive" way that the program cyclically get GPS data by itself?</p>
  
  <p>Thank you so much in advance. </p>
  
  <p>Here is "GPSReader" class which includes "LocationListner".  </p>
  
  <pre><code>package com.crowdsourcing.usgs;
  
  import android.app.Service;
  import android.content.Context;
  import android.content.Intent;
  import android.location.Criteria;
  import android.location.GpsStatus;
  import android.location.Location;
  import android.location.LocationListener;
  import android.location.LocationManager;
  import android.os.Bundle;
  import android.os.IBinder;
  import android.os.Binder;
  import android.provider.Settings;
  import android.widget.Toast;
  import java.util.Random;
  
  import Util.DateFormatter;
  
  
  /**
   * Created by TomokazuY on 9/14/2014.
   */
  public class GPSReader extends Service implements LocationListener, GpsStatus.Listener, GpsStatus.NmeaListener {
  
  private LocationManager locationManager;
  Location location;
  private String provider;
  //gpsLog, gpsTime will be passed to SensorReader
  public String gpsLog;
  private long gpsTime;
  private double latitude;
  private double longitude;
  private double altitude;
  private float bearing;
  private float accuracy;
  private String gpsProvider;
  public String nmea;
  
  private long lastUpdate = 0;
  //For global variable 
  Common common;
  
  public void onGpsStatusChanged(int event) {
  }
  
  
  public void onNmeaReceived(long timestamp, String nmea)
  {
      this.nmea = "NMEA Sentence: "+ nmea;
  }
  
  
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
  
      //For global variable
      common=((Common)getApplicationContext());
  
      locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
      // Define the criteria how to select the location provider -&gt; use default
      Criteria criteria = new Criteria();
      criteria.setAccuracy(Criteria.ACCURACY_FINE);
      criteria.setCostAllowed(false);
  
      provider = locationManager.getBestProvider(criteria, false);
      // the last known location of this provider
      location = locationManager.getLastKnownLocation(provider);
      common.initGPSTime = location.getTime();
  
      // Initialize the location fields
      if (location != null) {
          this.onLocationChanged(location);
      } else {
          intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
          startService(intent);
      }
      // location updates: at least 1 meter and 200 milli secs change
      // Both set to zero, which is the most aggressive setting.
      // You’ll get a location update if any change in location is detected at any time.
      // This setting can result in your app accessing the GPS provider as often as 50 –
      //This can drain a fully charge Samsung Galaxy S III in less than 3 hours.
      locationManager.requestLocationUpdates(provider, 0,0, this);
  
      locationManager.addNmeaListener(this);
  
      return START_STICKY;
  
  }
  @Override
  public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
      makeUseOfNewLocation(location);
  }
  @Override
  public void onStatusChanged(String s, int i, Bundle bundle) {
  
  }
  @Override
  public void onProviderEnabled(String s) {
      Toast.makeText(this, "Enabled new provider " + provider,
              Toast.LENGTH_SHORT).show();
  
  
  }
  @Override
  public void onProviderDisabled(String s) {
      Toast.makeText(this, "Disabled provider " + provider,
              Toast.LENGTH_SHORT).show();
  }
  
  public void makeUseOfNewLocation(Location loc) {
      latitude = loc.getLatitude();
      longitude = loc.getLongitude();
      altitude = loc.getAltitude();
      bearing = loc.getBearing();
      accuracy = loc.getAccuracy();
      gpsProvider = loc.getProvider();
  
      long curTime = System.currentTimeMillis();
      long currentGpsTime = loc.getTime();
      String currentGpsTimeString;
      common.gpsTime = currentGpsTime;
      currentGpsTimeString = DateFormatter.formatTimeStampM(common.gpsTime);
  
      common.gpsLog = ",lat:," + latitude + ",long:," + longitude + ", alt:," + altitude
              + ", accuracy:," + accuracy + ", provider:,"+ gpsProvider
  
              + ", GPSTime:," + DateFormatter.formatTimeStampM(common.gpsTime)
              + ", ForGraph:," + curTime + "," + currentGpsTime
              + ", NMEA:," + nmea;
  }
  
  @Override
  public void onDestroy() {
  
      if(locationManager != null){
          locationManager.removeUpdates(GPSReader.this);
      }
  }
  
  // Binder given to clients
  private final IBinder mBinder = new LocalBinder();
  // Random number generator
  private final Random mGenerator = new Random();
  
  /**
   * Class used for the client Binder.  Because we know this service always
   * runs in the same process as its clients, we don't need to deal with IPC.
   */
  public class LocalBinder extends Binder {
      GPSReader getService() {
          // Return this instance of LocalService so clients can call public methods
          return GPSReader.this;
      }
  }
  
  @Override
  public IBinder onBind(Intent intent) {
      return mBinder;
  }
  
  /** method for clients */
  public long getGpsTime() {
      return this.gpsTime;
  }
  
  //The function for gpsLog to be passed to SensorReader
  public String getGpsLog() {
      return gpsLog;
  }
  
  }
  </code></pre>
  
  <p>Also here is "SensorReader" class which has cyclically loop (There is part which assigns sampling ratio).</p>
  
  <pre><code>package com.crowdsourcing.usgs;
  
  import android.app.Service;
  import android.content.Context;
  import android.content.Intent;
  import android.hardware.Sensor;
  import android.hardware.SensorEvent;
  import android.hardware.SensorEventListener;
  import android.hardware.SensorManager;
  import android.os.IBinder;
  import android.widget.Toast;
  
  import Util.DateFormatter;
  import Util.FileCreator;
  
  /**
   * Created by SusanaLauH on 9/14/2014.
   */
  public class SensorReader extends Service implements SensorEventListener{
  
      //private final IBinder mBinder = new LocalBinder();
      private SensorManager mSensorManager;
      private Sensor accelerometerSensor, gyroscopeSensor, uncalGyroscopeSensor,
                     temperatureSensor, gravitySensor, lightSensor,
                     linearAccSensor, magnetSensor, uncalMagnetSensor,
                     airPressureSensor, humiditySensor, proximitySensor;
  
      Boolean test;
      Boolean isAccelerometer, isGyroscope, isUncalGyroscope, isMagnet, isUncalMagnet, isGravity,
              isLinearAcceleration, isTemperature, isProximity, isHumidity, isPressure, isLight;
  
      Boolean is1Hz, is5Hz, is50Hz, is100Hz;
  
      float xA, yA, zA = 0;// Accelerometer
      float xGy, yGy, zGy = 0; //Gyroscope
      float xGyu, yGyu, zGyu = 0; //Uncalibrated gyroscope
      float xGr, yGr, zGr; //Gravity
      float xLA, yLA, zLA;  //Linear Acceleration
      float xMg, yMg, zMg; //Magnetic Field
      float xMgu, yMgu, zMgu; //Uncalibrated magnetic field
      float temperature, airPressure, humidity, proximity, light;
  
      private long lastUpdate = 0;
      //private long lastUpdate = System.currentTimeMillis();
  
      int samplingRate = 1000; //Sampling rate = 1 Hz (units are in milliseconds)
      GPSReader gpsReader = new GPSReader();
  
      //Global variable
      Common common;
  
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
          Toast.makeText(this, "Starting reading sensors", Toast.LENGTH_SHORT).show();
  
          //Global variable
          common=((Common)getApplicationContext());
  
          common.initSysTime = System.currentTimeMillis();
  
          mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
  
          accelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
          gyroscopeSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
          uncalGyroscopeSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED);
          temperatureSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
          gravitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
          lightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
          linearAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
          magnetSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
          uncalMagnetSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED);
          airPressureSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
          humiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
          proximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
  
          //Using DELAY_FASTEST, the sensor will try to sensor the data as fast as possible.
          //Use more system resources
          mSensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, gyroscopeSensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, uncalGyroscopeSensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, temperatureSensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, gravitySensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, linearAccSensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, magnetSensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, uncalMagnetSensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, airPressureSensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, humiditySensor, SensorManager.SENSOR_DELAY_FASTEST);
          mSensorManager.registerListener(this, proximitySensor, SensorManager.SENSOR_DELAY_FASTEST);
  
  
         isAccelerometer = intent.getExtras().getBoolean("Accelerometer");
         isGyroscope =  intent.getExtras().getBoolean("Gyroscope");
         isUncalGyroscope =  intent.getExtras().getBoolean("UncalGyroscope");
         isGravity =  intent.getExtras().getBoolean("Gravity");
         isMagnet =  intent.getExtras().getBoolean("Magnet");
         isUncalMagnet =  intent.getExtras().getBoolean("UncalMagnet");
         isLinearAcceleration =  intent.getExtras().getBoolean("LinearAcceleration");
         isLight =  intent.getExtras().getBoolean(":Light");
         isProximity =  intent.getExtras().getBoolean("Proximity");
         isPressure =  intent.getExtras().getBoolean("Pressure");
         isTemperature =  intent.getExtras().getBoolean("Temperature");
         isHumidity = intent.getExtras().getBoolean("Humidity");
  
         is1Hz = intent.getExtras().getBoolean("1Hz");
         is5Hz = intent.getExtras().getBoolean("5Hz");
         is50Hz = intent.getExtras().getBoolean("50Hz");
         is100Hz = intent.getExtras().getBoolean("100Hz");
  
  
          //Toast.makeText(this, "Frequency 1: " + is1Hz, Toast.LENGTH_SHORT).show();
          //Toast.makeText(this, "Frequency 5: " + is5Hz, Toast.LENGTH_SHORT).show();
          //Toast.makeText(this, "Frequency 100: " + is100Hz, Toast.LENGTH_SHORT).show();
  
          if (is1Hz == true){
              samplingRate = 1000;
          }
  
          if (is5Hz == true){
              samplingRate = 200;
          }
  
          if (is50Hz == true){
              samplingRate = 20;
          }
  
          if (is100Hz == true) {//100 Hz
              //samplingRate = 10;
              samplingRate = 5;
  
          }
          //Detecting accelerometer
          if (accelerometerSensor != null) {
              Toast.makeText(this, "Accelerometer detected with MaxRange of: " + accelerometerSensor.getMaximumRange()
                                     + " and resolution of: " + accelerometerSensor.getResolution()
                                     + " and minDelay of: " + accelerometerSensor.getMinDelay(),
                                     Toast.LENGTH_SHORT).show();
          }else {
              Toast.makeText(this, "No accelerometer detected", Toast.LENGTH_SHORT).show();
          }
  
          //Detecting gyroscope
          if (gyroscopeSensor != null) {
              Toast.makeText(this, "Gyroscope detected", Toast.LENGTH_SHORT).show();
          }else {
              Toast.makeText(this, "No gyroscope detected", Toast.LENGTH_SHORT).show();
          }
  
          //Detecting temperature sensor
          if (temperatureSensor != null) {
              Toast.makeText(this, "Temperature Sensor detected", Toast.LENGTH_SHORT).show();
          }else {
              Toast.makeText(this, "No temperature sensor detected", Toast.LENGTH_SHORT).show();
          }
  
        //Detecting gravity sensor
          if (gravitySensor != null) {
              Toast.makeText(this, "Gravity Sensor detected", Toast.LENGTH_SHORT).show();
          }else {
              Toast.makeText(this, "No gravity sensor detected", Toast.LENGTH_SHORT).show();
          }
  
        //Detecting light sensor
          if (lightSensor != null) {
              Toast.makeText(this, "Light Sensor detected", Toast.LENGTH_SHORT).show();
          }else {
              Toast.makeText(this, "No light sensor detected", Toast.LENGTH_SHORT).show();
          }
  
         //Detecting magnetic field detector
          if (magnetSensor != null) {
              Toast.makeText(this, "Magnetic field Sensor detected", Toast.LENGTH_SHORT).show();
          }else {
              Toast.makeText(this, "No magnetic field sensor detected", Toast.LENGTH_SHORT).show();
          }
  
         //Detecting air pressure sensor
          if (airPressureSensor != null) {
              Toast.makeText(this, "Air pressure Sensor detected", Toast.LENGTH_SHORT).show();
          }else {
              Toast.makeText(this, "No Air pressure sensor detected", Toast.LENGTH_SHORT).show();
          }
  
          //Detecting humidity sensor
          if (humiditySensor != null) {
              Toast.makeText(this, "Humidity Sensor detected", Toast.LENGTH_SHORT).show();
          }else {
              Toast.makeText(this, "No humidity sensor detected", Toast.LENGTH_SHORT).show();
          }
  
          //Detecting proximity sensor
          if (proximitySensor != null) {
              Toast.makeText(this, "Proximity Sensor detected", Toast.LENGTH_SHORT).show();
          }else {
              Toast.makeText(this, "No proximity sensor detected", Toast.LENGTH_SHORT).show();
          }
  
          return START_STICKY;
      }
  
  
      @Override
      public void onSensorChanged(SensorEvent sensorEvent) {
          Sensor mSensor = sensorEvent.sensor;
  
          //Accelerometer
          if (mSensor.getType() == Sensor.TYPE_ACCELEROMETER &amp;&amp; isAccelerometer == true) {
              xA = sensorEvent.values[0];
              yA = sensorEvent.values[1];
              zA = sensorEvent.values[2];
          }
  
          //Gyroscope
          if (mSensor.getType() == Sensor.TYPE_GYROSCOPE &amp;&amp; isGyroscope == true) {
              xGy = sensorEvent.values[0];
              yGy = sensorEvent.values[1];
              zGy = sensorEvent.values[2];
          }
  
          //-Uncalibrated Gyroscope
          //Uncalibrated sensors provide more raw results and may include some bias,
          // but their measurements contain fewer jumps from corrections applied through calibration
          //Data is without drift compensation
          if (mSensor.getType() == Sensor.TYPE_GYROSCOPE_UNCALIBRATED &amp;&amp; isUncalGyroscope == true) {
              xGyu = sensorEvent.values[0];
              yGyu = sensorEvent.values[1];
              zGyu = sensorEvent.values[2];
          }
  
          //Temperature
          if (mSensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE &amp;&amp; isTemperature == true) {
              temperature = sensorEvent.values[0];
          }
  
          //Gravity
          if (mSensor.getType() == Sensor.TYPE_GRAVITY &amp;&amp; isGravity == true) {
              xGr = sensorEvent.values[0];
              yGr = sensorEvent.values[1];
              zGr = sensorEvent.values[2];
           }
  
           //Light
          if (mSensor.getType() == Sensor.TYPE_LIGHT &amp;&amp; isLight == true) {
              light = sensorEvent.values[0];
          }
  
          //Linear Acceleration
          if (mSensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION &amp;&amp; isLinearAcceleration == true) {
              xLA = sensorEvent.values[0];
              yLA = sensorEvent.values[1];
              zLA = sensorEvent.values[2];
          }
  
          //Magnetic Field
          if (mSensor.getType() == Sensor.TYPE_MAGNETIC_FIELD &amp;&amp; isMagnet == true) {
              xMg = sensorEvent.values[0];
              yMg = sensorEvent.values[1];
              zMg = sensorEvent.values[2];
          }
          //Uncalibrated Magnetic Field
          if (mSensor.getType() == Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED &amp;&amp; isUncalMagnet == true) {
              xMgu = sensorEvent.values[0];
              yMgu = sensorEvent.values[1];
              zMgu = sensorEvent.values[2];
          }
  
          //Air Pressure
          if (mSensor.getType() == Sensor.TYPE_PRESSURE &amp;&amp; isPressure == true) {
              airPressure = sensorEvent.values[0];
          }
  
          //Humidity
          if (mSensor.getType() == Sensor.TYPE_RELATIVE_HUMIDITY &amp;&amp; isHumidity ==true) {
              humidity = sensorEvent.values[0];
          }
  
          //Proximity
          if (mSensor.getType() == Sensor.TYPE_PROXIMITY &amp;&amp; isProximity == true) {
              proximity = sensorEvent.values[0];
          }
  
          //Logging data
          long curTime = System.currentTimeMillis();
          //long curTime = gpsReader.getGpsTime();
          //long gpsTime= common.gpsTime;
          //Get the GPS time from GPSReader
          String logTime = DateFormatter.formatTimeStampM(curTime);
          if ((curTime - lastUpdate) &gt; samplingRate) {
              lastUpdate = curTime;
              String log = logTime;
  
                  if (isAccelerometer == true){
                      log = log + ",Acc:," + xA + "," + yA + "," + zA;
                  }
  
                  if (isGyroscope == true) {
                      log = log + ",Gyro:," + xGy + "," + yGy + "," + zGy;
                  }
  
                  if (isUncalGyroscope == true) {
                      log = log + ",UncGyro:," + xGyu + "," + yGyu + "," + zGyu;
                  }
  
                  if (isGravity == true) {
                      log = log + ",Gravity:," + xGr + "," + yGr + "," + zGr;
                  }
  
                  if (isMagnet == true) {
                      log = log  + ",Mag:," + xMg + "," + yMg + "," + zMg;
                  }
  
                  if (isUncalMagnet == true){
                      log = log  + ",UncMag:," + xMgu + "," + yMgu + "," + zMgu;
                  }
  
                  if (isLinearAcceleration == true) {
                      log = log + ",Linear acc:," + xLA + "," + yLA + "," + zLA;
                  }
  
                  if (isLight == true){
                      log = log  + ",Light:," + light;
                  }
  
                  if (isTemperature == true) {
                      log = log + ",Temp:," + temperature;
                  }
  
                  if (isProximity == true){
                      log = log + ",Proximity:," + proximity;
                  }
  
                  if (isPressure == true){
                      log = log + ",AirPressure:," + airPressure;
                  }
  
                  if (isHumidity == true){
                      log = log + ",Humidity:," + humidity;
  
                  }
                     // + ", xA:" + xA + ", yA:" + yA + ", zA:" + zA
                     //+ ", xG:" + xGy + ", yG:" + yGy + ", zG: " + zGy + ", "
                     // + ", xGu:" + xGyu + ", yGu:" + yGyu + ", zGu: " + zGyu + ", "
                      //+ ",Acc:," + xA + "," + yA + "," + zA
                     // + ",Gyro:," + xGy + "," + yGy + "," + zGy
                     //+ ",UncGyro:," + xGyu + "," + yGyu + "," + zGyu
                      //+ ",Temp:," + temperature
                      //+ ",Gravity:," + xGr + "," + yGr + "," + zGr
                      //+ ",Light:," + xA + "," + yA + "," + zA
                      //+ ",Linear acc:," + xLA + "," + yLA + "," + zLA
                      //+ ",Mag:," + xMg + "," + yMg + "," + zMg
                      //+ ",UncMag:," + xMgu + "," + yMgu + "," + zMgu
                      //+ ",Air:," + airPressure
                      //+ ",Humidity:," + humidity
                     // + ",Proximity:," + proximity
  
             // log = log + gpsReader.getGpsLog();
  
                      //+ common.gpsTime;
                   log = log   + common.gpsLog;
  
  
              FileCreator file = new FileCreator();
              file.write("Logs", log);
          }
  
      }
  
      @Override
      public void onAccuracyChanged(Sensor sensor, int i) {
      //Do nothing
      }
  
      // To provide binding for a service, you must implement the onBind() callback method.
      // This method returns an IBinder object that defines the programming interface that
      // clients can use to interact with the service.
      @Override
      public IBinder onBind(Intent intent) {
          //return mBinder;
          return null;
      }
      @Override
      public void onDestroy() {
          //Toast.makeText(this, "Service done", Toast.LENGTH_SHORT).show();
          mSensorManager.unregisterListener(this);
      }
  
   }
  </code></pre>
  
  <p>And "Common" class for global variable</p>
  
  <pre><code>package com.crowdsourcing.usgs;
  import android.app.Application;
  
  
  /**
   * Created by tomokazy on 9/20/14.
   */
  public class Common extends Application{
      // Global
      long initSysTime;
      long initGPSTime;
      long gpsTime;
      String gpsLog;
      public void init(){
          gpsTime = 0;
          gpsLog = "";
      }
  
  }
  </code></pre>