title: Background location update in Android periodically
body: <p>I am Using Fused Location Provider Google api client to get the location for every 5 minutes . It is updating both in background and also when the application is killed . But it is Stopped updating after some 2 to 3 days . i have tested in most of the android devices.</p>
  <p>I am calling this Service from an Activity and i am Killing the application, it is sending location updates for every 5 minutes for almost 3 days after that it is getting stopped .I tried So many times.</p>
  <pre><code>public class GPSTracker extends Service implements
          GoogleApiClient.ConnectionCallbacks,
          GoogleApiClient.OnConnectionFailedListener,
          com.google.android.gms.location.LocationListener {
  
      protected static final String TAG = &quot;Location...&quot;;
      private Context mContext = this;
  
  
      /**
       * Tracks the status of the location updates request.
       */
      public static Boolean mRequestingLocationUpdates;
      /**
       * Time when the location was updated represented as a String.
       */
      protected String mLastUpdateTime;
      /**
       * Provides the entry point to Google Play services.
       */
      protected GoogleApiClient mGoogleApiClient;
      /**
       * Stores parameters for requests to the FusedLocationProviderApi.
       */
      protected LocationRequest mLocationRequest;
  
      /**
       * Represents a geographical location.
       */
      protected Location mCurrentLocation;
      public static boolean isEnded = false;
  
  
      @Override
      public void onCreate() {
          super.onCreate();
  
          buildGoogleApiClient();
      }
  
      @Nullable
      @Override
      public IBinder onBind(Intent intent) {
          return null;
      }
  
  
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
  
          Log.d(&quot;LOC&quot;, &quot;Service init...&quot;);
          isEnded = false;
          mRequestingLocationUpdates = false;
          mLastUpdateTime = &quot;&quot;;
          // buildGoogleApiClient();
          if (mGoogleApiClient.isConnected() &amp;&amp; mRequestingLocationUpdates) {
              startLocationUpdates();
          }
          return START_STICKY;
      }
  
  
  
  
      @Override
      public void onConnected(Bundle bundle) {
  
          startLocationUpdates();
      }
  
      @Override
      public void onConnectionSuspended(int i) {
          // The connection to Google Play services was lost for some reason. We call connect() to
          // attempt to re-establish the connection.
          Log.i(TAG, &quot;Connection suspended==&quot;);
          mGoogleApiClient.connect();
      }
  
      @Override
      public void onLocationChanged(Location location) {
          mCurrentLocation = location;
          mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
          double latitude = location.getLatitude();
          double longitude = location.getLongitude();
  
          StringBuilder stringBuilder = new StringBuilder();
          StringBuilder latlong = stringBuilder.append(latitude + &quot;,&quot; + longitude);
  
          Calendar cal = Calendar.getInstance();
          String zone = TimeZone.getDefault().getDisplayName(false, android.icu.util.TimeZone.SHORT);
          SimpleDateFormat formatter = new SimpleDateFormat(&quot;dd-MMM 'at' h:mm a&quot;);
          Date date = new Date();
          String localtime = (formatter.format(date)).toString();
  
          Date myDate = new Date();
  
          Calendar calendar = Calendar.getInstance();
          calendar.setTimeZone(TimeZone.getTimeZone(&quot;UTC&quot;));
          calendar.setTime(myDate);
          date = calendar.getTime();
          SimpleDateFormat dateFormatter = new SimpleDateFormat(&quot;yyyy-MM-dd'T'HH:mm:ss zz&quot;);
          dateFormatter.setTimeZone(TimeZone.getTimeZone(&quot;UTC&quot;));
          String utc = dateFormatter.format(date);
  
        //  DateFormat df = DateFormat.getTimeInstance();
        //  df.setTimeZone(TimeZone.getTimeZone(&quot;gmt&quot;));
        //  String gmtTime = df.format(new Date());
  
          String model = Build.MODEL;
  
          String reqString = Build.VERSION.RELEASE
                  + &quot; &quot; + Build.VERSION_CODES.class.getFields()[android.os.Build.VERSION.SDK_INT].getName();
  
          // Date currentTime = Calendar.getInstance().getTime();
          // String localtime = currentTime.toString();
  
          PreferencesClass preferencesClass = new PreferencesClass(mContext);
          String id = preferencesClass.getFingerPrint();
  
          Data data = null;
          try {
              JSONObject jsonObject = new JSONObject();
              jsonObject.put(&quot;userId&quot;, id);
              jsonObject.put(&quot;latLon&quot;, latlong);
              jsonObject.put(&quot;timeZone&quot;, zone);
              jsonObject.put(&quot;localTime&quot;, localtime);
              jsonObject.put(&quot;osVersion&quot;,reqString);
              jsonObject.put(&quot;phoneModel&quot;,model);
              jsonObject.put(&quot;utcTime&quot;,utc);
              data = new Data();
              data.setData(jsonObject.toString());
  
              if (data != null) {
  
                  if (Utility.isConnectingToInternet(mContext)) {
  
                     // boolean isChecked = preferencesClass.getIsChecked();
                    //  if (isChecked){
  
                          LocationWebServiceMgr locationWebServiceMgr = new LocationWebServiceMgr();
                          locationWebServiceMgr.Location(data, new CallBackInterface() {
                              @Override
                              public void onResponse(ArrayList&lt;Object&gt; objects, ResponseMetaData responseMetaData) {
  
                                  Log.d(TAG, &quot;onResponse: Succesfully added the location to server&quot;);
                                  // Toast.makeText(getApplicationContext(), &quot;added to server&quot;, Toast.LENGTH_LONG).show();
                              }
  
                              @Override
                              public void onFailure(ResponseMetaData t) {
                              }
                          });
  
                     // } else {
                       //   Log.d(&quot;serverCall&quot;, &quot;Location Permission not available &quot;);
  
                    //  }
  
                  } else {
  
                      Log.e(&quot;serverCall&quot;, &quot;Network not available&quot;);
  
                  }
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  
      @Override
      public void onConnectionFailed(ConnectionResult connectionResult) {
          // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
          // onConnectionFailed.
          Log.i(TAG, &quot;Connection failed: ConnectionResult.getErrorCode() = &quot; + connectionResult.getErrorCode());
      }
  
      /**
       * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the
       * LocationServices API.
       */
      protected synchronized void buildGoogleApiClient() {
          Log.i(TAG, &quot;Building GoogleApiClient===&quot;);
          mGoogleApiClient = new GoogleApiClient.Builder(this)
                  .addConnectionCallbacks(this)
                  .addOnConnectionFailedListener(this)
                  .addApi(LocationServices.API)
                  .build();
  
          createLocationRequest();
      }
  
      /**
       * Sets up the location request. Android has two location request settings:
       * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control
       * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
       * the AndroidManifest.xml.
       * &lt;p/&gt;
       * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
       * interval (5 seconds), the Fused Location Provider API returns location updates that are
       * accurate to within a few feet.
       * &lt;p/&gt;
       * These settings are appropriate for mapping applications that show real-time location
       * updates.
       */
      protected void createLocationRequest() {
          mGoogleApiClient.connect();
          mLocationRequest = new LocationRequest();
  
          // Sets the desired interval for active location updates. This interval is
          // inexact. You may not receive updates at all if no location sources are available, or
          // you may receive them slower than requested. You may also receive updates faster than
          // requested if other applications are requesting location at a faster interval.
          mLocationRequest.setInterval(Constants.UPDATE_INTERVAL_IN_MILLISECONDS);
  
          // Sets the fastest rate for active location updates. This interval is exact, and your
          // application will never receive updates faster than this value.
          mLocationRequest.setFastestInterval(Constants.FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
  
         // mLocationRequest.setSmallestDisplacement(Constants.DISPLACEMENT);
  
          //mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
      }
  
      /**
       * Requests location updates from the FusedLocationApi.
       */
      protected void startLocationUpdates() {
          if (!mRequestingLocationUpdates) {
              mRequestingLocationUpdates = true;
  
              // The final argument to {@code requestLocationUpdates()} is a LocationListener
              if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp; ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                  // TODO: Consider calling
                  //    ActivityCompat#requestPermissions
                  // here to request the missing permissions, and then overriding
                  //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                  //                                          int[] grantResults)
                  // to handle the case where the user grants the permission. See the documentation
                  // for ActivityCompat#requestPermissions for more details.
                  return;
              }
              LocationServices.FusedLocationApi.requestLocationUpdates(
                      mGoogleApiClient, mLocationRequest, this);
              Log.i(TAG, &quot; startLocationUpdates===&quot;);
              isEnded = true;
          }
      }
  }
  </code></pre>