Use Fused location provider in Android set your interval in that:

For an example create your activity like this:

public class LocationActivity extends Activity implements
        LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "LocationActivity";
    private static final long INTERVAL = 1000 * 10;
    private static final long FASTEST_INTERVAL = 1000 * 5;
    Button btnFusedLocation;
    TextView tvLocation;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation;
    String mLastUpdateTime;

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate ...............................");
        //show error dialog if GoolglePlayServices not available
        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        setContentView(R.layout.activity_main);
        tvLocation = (TextView) findViewById(R.id.tvLocation);

        btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
        btnFusedLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                updateUI();
            }
        });

    }

    @Override
    public void onStart() {
        super.onStart();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
            Log.d(TAG, "Location update resumed .....................");
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop fired ..............");
        mGoogleApiClient.disconnect();
        Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
        startLocationUpdates();
    }

    protected void startLocationUpdates() {
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
        Log.d(TAG, "Location update started ..............: ");
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "Connection failed: " + connectionResult.toString());
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "Firing onLocationChanged..............................................");
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
    }

    private void updateUI() {
        Log.d(TAG, "UI update initiated .............");
        if (null != mCurrentLocation) {
            String lat = String.valueOf(mCurrentLocation.getLatitude());
            String lng = String.valueOf(mCurrentLocation.getLongitude());
            tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
                    "Latitude: " + lat + "\n" +
                    "Longitude: " + lng + "\n" +
                    "Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
                    "Provider: " + mCurrentLocation.getProvider());
        } else {
            Log.d(TAG, "location is null ...............");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
        Log.d(TAG, "Location update stopped .......................");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
            Log.d(TAG, "Location update resumed .....................");
        }
    }
}

Google play services required:

Answer from Pushpendra on Stack Overflow
🌐
Howtodoandroid
howtodoandroid.com › continuous-location-updates-android
How to get continuous location updates in Android - HowToDoAndroid - Android Development Tutorials
{ context?.let { ContextCompat.startForegroundService(it, Intent(it, LocationService::class.java)) } } } Also, don't forget to add the broadcast receiver on the manifeats.xml file inside the application tag. <receiver android:name=".BootDeviceReceivers" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> That's it. Now you can fetch the location continuously and send the location to the server.
Top answer
1 of 4
38

Use Fused location provider in Android set your interval in that:

For an example create your activity like this:

public class LocationActivity extends Activity implements
        LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "LocationActivity";
    private static final long INTERVAL = 1000 * 10;
    private static final long FASTEST_INTERVAL = 1000 * 5;
    Button btnFusedLocation;
    TextView tvLocation;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation;
    String mLastUpdateTime;

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate ...............................");
        //show error dialog if GoolglePlayServices not available
        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        setContentView(R.layout.activity_main);
        tvLocation = (TextView) findViewById(R.id.tvLocation);

        btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
        btnFusedLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                updateUI();
            }
        });

    }

    @Override
    public void onStart() {
        super.onStart();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
            Log.d(TAG, "Location update resumed .....................");
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop fired ..............");
        mGoogleApiClient.disconnect();
        Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
        startLocationUpdates();
    }

    protected void startLocationUpdates() {
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
        Log.d(TAG, "Location update started ..............: ");
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "Connection failed: " + connectionResult.toString());
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "Firing onLocationChanged..............................................");
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
    }

    private void updateUI() {
        Log.d(TAG, "UI update initiated .............");
        if (null != mCurrentLocation) {
            String lat = String.valueOf(mCurrentLocation.getLatitude());
            String lng = String.valueOf(mCurrentLocation.getLongitude());
            tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
                    "Latitude: " + lat + "\n" +
                    "Longitude: " + lng + "\n" +
                    "Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
                    "Provider: " + mCurrentLocation.getProvider());
        } else {
            Log.d(TAG, "location is null ...............");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
        Log.d(TAG, "Location update stopped .......................");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
            Log.d(TAG, "Location update resumed .....................");
        }
    }
}

Google play services required:

2 of 4
10

To get continiuos location update, you can refer to the above provided answers .

But You can also make use of LocationServices which is faster than other approaches and much easy and efficient to get location.

This approach is quit long but kindly follow all the provided steps

So let me provide a brief working :

  1. Add these two dependencies in your gradle app file

    implementation 'com.google.android.gms:play-services-maps:17.0.0' implementation 'com.google.android.gms:play-services-location:17.0.0'

  2. Add these permissions in the manifest file outside applicationtag

  3. Declare variable outside onCreate

    private FusedLocationProviderClient fusedLocationClient; private LocationRequest mLocationRequest; private LocationCallback mlocationCallback; private LocationSettingsRequest.Builder builder; private static final int REQUEST_CHECK_SETTINGS = 102;

  4. Now inside onCreate :

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); fetchLastLocation(); mlocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { if (locationResult == null) { return; } for (Location location : locationResult.getLocations()) { // Update UI with location data // ... Log.e("CONTINIOUSLOC: ", location.toString()); } }; };

    mLocationRequest = createLocationRequest(); builder = new LocationSettingsRequest.Builder() .addLocationRequest(mLocationRequest); checkLocationSetting(builder);

  5. No define fetchLastLocation method

    private void fetchLastLocation() {

         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
             if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                 // TODO: Consider calling
                 //    Activity#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 Activity#requestPermissions for more details.
    

    // Toast.makeText(MainActivity.this, "Permission not granted, Kindly allow permission", Toast.LENGTH_LONG).show(); showPermissionAlert(); return; } } fusedLocationClient.getLastLocation() .addOnSuccessListener(this, new OnSuccessListener() { @Override public void onSuccess(Location location) { // Got last known location. In some rare situations this can be null. if (location != null) { // Logic to handle location object Log.e("LAST LOCATION: ", location.toString()); // You will get your last location here } } });

     }
    
  6. Now define other two method for permission request

    @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 123: { // If request is cancelled, the result arrays are empty. if (grantResults[0] == PackageManager.PERMISSION_DENIED) { // permission was denied, show alert to explain permission showPermissionAlert(); }else{ //permission is granted now start a background service if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { fetchLastLocation(); } } } } }

     private void showPermissionAlert(){
         if (ActivityCompat.checkSelfPermission(MainHomeActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                 && ActivityCompat.checkSelfPermission(MainHomeActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
             ActivityCompat.requestPermissions(MainHomeActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 123);
         }
     }
    
  7. now define createLocationRequest method and checkLocationSetting method :

    protected LocationRequest createLocationRequest() { LocationRequest mLocationRequest = LocationRequest.create(); mLocationRequest.setInterval(30000); mLocationRequest.setFastestInterval(10000); mLocationRequest.setSmallestDisplacement(30); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); return mLocationRequest; }

    private void checkLocationSetting(LocationSettingsRequest.Builder builder) {

         SettingsClient client = LocationServices.getSettingsClient(this);
         Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
    
         task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
             @Override
             public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                 // All location settings are satisfied. The client can initialize
                 // location requests here.
                 // ...
                 startLocationUpdates();
                 return;
             }
         });
    
         task.addOnFailureListener(this, new OnFailureListener() {
             @Override
             public void onFailure(@NonNull final Exception e) {
                 if (e instanceof ResolvableApiException) {
                     // Location settings are not satisfied, but this can be fixed
                     AlertDialog.Builder builder1 = new AlertDialog.Builder(mContext);
                     builder1.setTitle("Continious Location Request");
                     builder1.setMessage("This request is essential to get location update continiously");
                     builder1.create();
                     builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                         @Override
                         public void onClick(DialogInterface dialog, int which) {
                             ResolvableApiException resolvable = (ResolvableApiException) e;
                             try {
                                 resolvable.startResolutionForResult(MainHomeActivity.this,
                                         REQUEST_CHECK_SETTINGS);
                             } catch (IntentSender.SendIntentException e1) {
                                 e1.printStackTrace();
                             }
                         }
                     });
                     builder1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                         @Override
                         public void onClick(DialogInterface dialog, int which) {
                             Toast.makeText(mContext, "Location update permission not granted", Toast.LENGTH_LONG).show();
                         }
                     });
                     builder1.show();
                 }
             }
         });
    
     }
    
     @Override
     protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
         if (requestCode == REQUEST_CHECK_SETTINGS) {
             if (resultCode == RESULT_OK) {
                 // All location settings are satisfied. The client can initialize
                 // location requests here.
                  startLocationUpdates();
             }
             else {
                 checkLocationSetting(builder);
             }
         }
     }
    
  8. now atlast define startLocationUpdates and stopLocationUpdates method :

    public void startLocationUpdates() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // Activity#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 Activity#requestPermissions for more details. return; } } fusedLocationClient.requestLocationUpdates(mLocationRequest, mlocationCallback, null /* Looper */); }

    private void stopLocationUpdates() { fusedLocationClient.removeLocationUpdates(mlocationCallback); }

Note : Replace context with your class context and call stopLocationUpdates() inside onDestroy method of your class

Note : For any futher information or doubt you can refer to :

https://developer.android.com/training/location/retrieve-current https://developer.android.com/training/location/change-location-settings https://developer.android.com/training/location/receive-location-updates

You will get your location in Logcat.

Hope this will hope you or somebody else !

🌐
Medium
medium.com › android-beginners › how-to-get-continuous-location-updates-in-android-9bb308d468d3
How to get continuous location updates in Android | by Velmurugan Murugesan | Howtodoandroid | Medium
March 15, 2021 - { context?.let { ContextCompat.startForegroundService(it, Intent(it, LocationService::class.java)) } } } That’s it. Now you can able to fetch the location continuously and send the location to the server. Download this example from GITHUB. Thanks for reading. Please provide your feedback in the comments. Originally published at https://howtodoandroid.com on March 15, 2021. ... best android developers medium publication focused on beginners to learn the android concepts very easily.
Top answer
1 of 2
7

I am glad that I finally found it. The code is short. I have used LocationRequest and LocationCallback method. Also, I have used the fusedLocationProviderClient for requestLocationUpdates.

public class MainActivity extends AppCompatActivity {

    private FusedLocationProviderClient fusedLocationProviderClient;
    TextView locationTextView;
    LocationRequest locationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        locationTextView = findViewById(R.id.location_text);

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

//Not the best practices to get runtime permissions, but still here I ask permissions.
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
        }

//Instantiating the Location request and setting the priority and the interval I need to update the location.
        locationRequest = locationRequest.create();
        locationRequest.setInterval(100);
        locationRequest.setFastestInterval(50);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

//instantiating the LocationCallBack
        LocationCallback locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if (locationResult != null) {
                    if (locationResult == null) {
                        return;
                    }
     //Showing the latitude, longitude and accuracy on the home screen.
                    for (Location location : locationResult.getLocations()) {
                        locationTextView.setText(MessageFormat.format("Lat: {0} Long: {1} Accuracy: {2}", location.getLatitude(),
                                location.getLongitude(), location.getAccuracy()));
                    }
                }
            }
        };
        fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
    }
}

In activity_main.xml

<TextView
        android:id="@+id/location_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/andika"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Also, before all these, I have added this in my dependencies

    implementation 'com.google.android.gms:play-services-location:17.0.0'

And this in my Manifest


    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

And this keeps on updating in intervals you choose

2 of 2
1

Hi so continious location update is something you should avoid as it drains battery. You can use locationlistner where you could listen to location change. Say you want to update the location and get the attitude and longitude on every 10 meter change.

Sample code to check last,long every 100 meter

class LocationService : Service(), LocationListener {
protected var locationManager: LocationManager? = null
var checkGPS = false
var checkNetwork = false

// boolean canGetLocation = false;
var loc: Location? = null

//    double latitude;
//    double longitude;
override fun onBind(intent: Intent): IBinder? {
    return null
}

override fun onLocationChanged(location: Location) {
    // Toast.makeText(getApplicationContext(), Double.toString(location.getLatitude()) + location.getLongitude(), Toast.LENGTH_LONG).show();
}

override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
override fun onCreate() {
    super.onCreate()
    location
}

        Toast.makeText(getApplicationContext(), Double.toString(latitude) + longitude + "from method", Toast.LENGTH_LONG).show();
private val location: Location?
    private get() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) !=
            PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
        }
        locationManager = applicationContext
            .getSystemService(LOCATION_SERVICE) as LocationManager
        checkGPS = locationManager!!
            .isProviderEnabled(LocationManager.GPS_PROVIDER)
        checkNetwork = locationManager!!
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        locationManager!!.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MIN_TIME_BW_UPDATES,
            MIN_DISTANCE_CHANGE_FOR_UPDATES.toFloat(), this
        )
        if (locationManager != null) {
            val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
            fusedLocationClient.lastLocation.addOnSuccessListener { location ->
                if (location != null) {
                    Toast.makeText(
                        applicationContext,
                        java.lang.Double.toString(location.latitude) + location.longitude + "from method",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
        }
                Toast.makeText(getApplicationContext(), Double.toString(latitude) + longitude + "from method", Toast.LENGTH_LONG).show();
        return loc
    }

companion object {
    private const val MIN_DISTANCE_CHANGE_FOR_UPDATES: Long = 100
    private const val MIN_TIME_BW_UPDATES: Long = 30
}

}

Top answer
1 of 1
4

Have you tried debugging to make sure your service is being hit?

This might sound silly, but have you checked if your service is registered in your manifest? I know I've definitely run into that issue.

<service android:name=".LocationService"
        android:label="Location Service"
        android:exported="true"
        android:enabled="true"
        android:process=":location_background_service"/>

For getting the location, when I set mine up, I created a class that implemented android.location.LocationListener.

private class LocationListener implements android.location.LocationListener {
    Location mLastLocation;

    public LocationListener(String provider) {
        Log.e(TAG, "LocationListener " + provider);
        mLastLocation = new Location(provider);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG, "onLocationChanged: " + location);
        mLastLocation.set(location);
    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.e(TAG, "onProviderDisabled: " + provider);
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.e(TAG, "onProviderEnabled: " + provider);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.e(TAG, "onStatusChanged: " + provider);
    }
}

You can create multiple instances for different providers. In my case, I ended up using 2.

LocationListener[] mLocationListeners = new LocationListener[]{
        new LocationListener(LocationManager.GPS_PROVIDER),
        new LocationListener(LocationManager.NETWORK_PROVIDER)
};

Then I initialized a LocationManager that can set a polling rate for each a LocationListener.

private void initializeLocationManager() {
    Log.e(TAG, "initializeLocationManager");
    if (mLocationManager == null) {
        mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    }
}

Then in your Service onCreate function, initialize your LocationManager, and use one of the listeners as your main source and the other as a fallback.

try {
        mLocationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER,
                5 * 60 * 1000, //5 Minutes
                1F /*METERS*/,
                mLocationListeners[0]
        );
    } catch (java.lang.SecurityException ex) {
        Log.e(TAG, "failed to request location update. Insufficient permissions. ", ex);
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,
                    5 * 60 * 1000, //5 Minutes
                    1F /*METERS*/,
                    mLocationListeners[1]
            );
        } catch (java.lang.SecurityException e) {
            Log.e(TAG, "failed to request location update. Insufficient permissions. ", e);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Network provider does not exist.", e);
        }
    } catch (IllegalArgumentException ex) {
        Log.e(TAG, "Network provider does not exist.", ex);
    }
}

(Sorry if this code is gross, it's a quick and dirty example.)

🌐
Huihoo
docs.huihoo.com › android › 4.4 › training › location › receive-location-updates.html
Receiving Location Updates | Android Developers - Huihoo
To get periodic location updates from Location Services, you send a request using a location client. Depending on the form of the request, Location Services either invokes a callback method and passes in a Location object, or issues an Intent that contains the location in its extended data.
Find elsewhere
🌐
Google
codelabs.developers.google.com › codelabs › while-in-use-location
Receive location updates in Android with Kotlin | Google Codelabs
March 27, 2026 - If you wish to continue receiving updates in that situation, you need to create a foreground Service and associate it with a Notification. In addition, if you want to use the same Service to request location updates when your app is visible and when the user navigates away from your app, you ...
🌐
Android Developers
developer.android.com › core areas › sensors and location › request location updates
Request location updates | Sensors and location | Android Developers
This document explains how to request regular updates about a device's location using the Fused Location Provider's requestLocationUpdates() method in Android.
Top answer
1 of 1
1

Try to use this helper class to start location updates :

Edited :

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class LocationHandler implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private static final String TAG = LocationHandler.class.getSimpleName();
    private Context mContext;
    public GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private Location mCurrentLocation;
    private Handler handler;
    public boolean isLocationAvailable = false;

    public LocationHandler(Context context, Handler mHandler) {
        this.mContext = context;
        this.handler = mHandler;
        buildGoogleApiClient();
    }

    @Override
    public void onConnected(Bundle bundle) {
        LocationManager locationManager = (LocationManager)
                this.mContext.getSystemService(Context.LOCATION_SERVICE);
        isLocationAvailable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (mCurrentLocation == null) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }
        isLocationAvailable = true;
        startLocationUpdates();
        this.handler.sendEmptyMessage(0);
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.d(TAG, "onConnectionSuspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
    }


    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "onLocationChanged = " + location.getLatitude());
        mCurrentLocation = location;
    }

    /**
     * To create location request
     */
    public void createLocationRequest() {
        Log.d(TAG, "createLocationRequest");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(60 * 1000);
        mLocationRequest.setFastestInterval(60 * 1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    }

    /**
     * To build google client
     */
    public synchronized void buildGoogleApiClient() {
        Log.d(TAG, "buildGoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this.mContext)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
        mGoogleApiClient.connect();
    }

    /**
     * To start location updates
     */
    public void startLocationUpdates() {
        Log.d(TAG, "startLocationUpdates");
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    /**
     * To stop location updates
     */
    public void stopLocationUpdates() {
        Log.d(TAG, "stopLocationUpdates");
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    /**
     * To get current location
     *
     * @return A location object
     */
    public Location getCurrentLocation() {
        return mCurrentLocation;
    }
}

In your activity do :

  1. Check for internet connection.
  2. Check for GPS is enabled or not.
  3. Start location updates if both of above are true.

Like this :

Activity where we get location change updates :

import android.app.Activity;
import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.lang.ref.WeakReference;


public class MainActivity extends Activity {

    private LocationHandler locationUtility;
    private LocationManager mLocationManager = null;
    private IncomingHandler incomingHandler;

    /**
     * Handler of incoming messages from clients.
     */
    private static class IncomingHandler extends Handler {
        private WeakReference<MainActivity> mainActivityWeakReference;

        public IncomingHandler(MainActivity mainActivity) {
            mainActivityWeakReference = new WeakReference<>(mainActivity);
        }

        @Override
        public void handleMessage(Message message) {
            if (mainActivityWeakReference != null) {
                MainActivity mainActivity = mainActivityWeakReference.get();
                switch (message.what) {
                    case 0:

                        boolean isConnected = // check internet is connected
                        boolean isGPSEnabled = mainActivity.mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                        boolean isNetworkEnabled = mainActivity.mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                        if (!isConnected) {
                            // show alert or toast
                        }
                        if (!(isGPSEnabled && isNetworkEnabled)) {
                            // show alert or toast
                        }
                        if (mainActivity.locationUtility.mGoogleApiClient.isConnected()) {
                            mainActivity.locationUtility.startLocationUpdates(); // start updates
                        }
                        break;
                }
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        incomingHandler = new IncomingHandler(this);
        locationUtility = new LocationHandler(MainActivity.this, incomingHandler);
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

}

When you want to stop updates use :

if (locationUtility.mGoogleApiClient.isConnected()) {
            locationUtility.stopLocationUpdates();
        }

This will update location even though your activity is paused unless it destroyed.

Also not to forget adding following permission in Manifest.xml :

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Thanks.

Top answer
1 of 2
3

you can use Location Request and fused location Api to update and fetch user location in a selected interval:

this is the Main activity:

 public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        }
        else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {

            mLastLocation = location;
            if (mCurrLocationMarker != null) {
                mCurrLocationMarker.remove();
            }

            //Place current location marker
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("Current Position");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
            mCurrLocationMarker = mMap.addMarker(markerOptions);

            //move map camera
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

            //stop location updates
            if (mGoogleApiClient != null) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            }

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    public boolean checkLocationPermission(){
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Asking user if explanation is needed
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

                //Prompt the user once explanation has been shown
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted. Do the
                    // contacts-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }

                } else {

                    // Permission denied, Disable the functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other permissions this app might request.
            // You can add here other case statements according to your requirement.
        }
    }
}

And the manifest.xml file:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key"/>

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
</application>

the project will:

  1. Retreive user location at a specified interval using fused location api.

  2. Ask specific runtime permission for location update

  3. Draw a marker on google map based on user real time location..update

for details you can see this link:https://www.androidtutorialpoint.com/intermediate/android-map-app-showing-current-location-android/

2 of 2
2

You can add a Location listner and update location on location change

 public void onLocationChanged(Location location) {
 //Do some thing with new location
}

but if you still want to update location every 10 seconds then use a handler to loop for every 10 seconds and update your location inside handler

   Handler h = new Handler();
int delay = 10000; 

h.postDelayed(new Runnable(){
    public void run(){
        //Update Location here
        h.postDelayed(this, delay);
    }
}, delay);
🌐
YouTube
youtube.com › watch
Android Get Current Location Continuously | Location Service | Fused Location Provider API - YouTube
Android Get Current Location Continuously | Location Service | Fused Location Provider APIIn this tutorial, we will implement a foreground location service w...
Published   May 20, 2020
🌐
YouTube
youtube.com › velmurugan murugesan
How to get continuous location updates in Android - YouTube
I am going to explain how to update the live location to the server every some interval. For example, sending live location to the server for every 1 minute....
Published   March 15, 2021
Views   4K
🌐
Android Developers
developer.android.com › about › versions › oreo › background-location-limits
Background Location Limits | Android Developers
April 29, 2024 - Note: If your app needs access to location history that contains time-frequent updates, use the batched version of the Fused Location Provider API elements, such as the FusedLocationProviderApi interface.
🌐
Google
developers.google.com › google play services › fusedlocationproviderclient
FusedLocationProviderClient | Google Play services | Google for Developers
October 31, 2024 - To receive location updates in the background, apps need the ACCESS_BACKGROUND_LOCATION permission or must use a foreground location service. Use getCurrentLocation for a single location fix and requestLocationUpdates for continuous location ...
🌐
Android Developers
stuff.mit.edu › afs › sipb › project › android › docs › training › basics › location › currentlocation.html
Obtaining the Current Location | Android Developers
In its simplest form, you register an event listener, identify the location manager from which you'd like to receive location updates, and specify the minimum time and distance intervals at which to receive location updates.
🌐
Stack Overflow
stackoverflow.com › questions › 44995445 › how-to-get-real-time-current-location-update-as-we-walk
java - How to get real time current location update as we walk - Stack Overflow
public class LocationFetcher implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { public GoogleApiClient googleApiClient; Context context; private LocationRequest locationRequest; public LocationFetcher(Context context) { this.context = context; googleApiClient = new GoogleApiClient.Builder(context) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); locationRequest = new LocationRequest(); } public void connectGps() { googleApiClient.connect(); } pub
🌐
Code Redirect
coderedirect.com › questions › 170421 › how-can-i-get-continuous-location-updates-in-android-like-in-google-maps
[Solved] Gps How can I get continuous location updates in Android like in Google Maps? - Code Redirect
Then in OnCreate() of your Activity to register the GPSStatus.Listener: mService = (LocationManager)getSystemService(Context.LOCATION_SERVICE); mService.addGpsStatusListener(this); In the GPSTest app, the list of currently available satellites is shown on the screen with each GPSStatus.Listener update, based on this code: https://github.com/barbeau/gpstest/blob/master/GPSTest/src/main/java/com/android/gpstest/GpsStatusFragment.java