The LocationListener interface and the LocationManager class are used to determine the location. First you need to create a listener object that implements the LocationListener interface:
LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { //вызывается при обновлении данных о местоположении } @Override public void onStatusChanged(String s, int i, Bundle bundle) { //вызывается при изменении статуса указанного провайдера } @Override public void onProviderEnabled(String provider) { //вызывается при включении указанного провайдера } @Override public void onProviderDisabled(String provider) { //вызывается при выключении указанного провайдера } };
In order for the listener to receive the location data, you need to request it from the system as follows:
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); locationManager.requestLocationUpdates(provider, minTime, minDistance, locationListener);
The provider is one of the location providers. There are two main providers: LocationManager.GPS_PROVIDER and LocationManager.NETWORK_PROVIDER. The list of available providers can be obtained using the function:
List<String> providersList = locationManager.getAllProviders();
minTime - the time interval in milliseconds after which location updates should arrive.
minDistance - the minimum distance at which the location is updated.
locationListener is our location listener.
For the application to work, you must define the following permissions in the manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You can check for these permissions during program execution as follows:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //у приложения нет разрешений на определение местоположения return; } locationManager.requestLocationUpdates(provider, minTime, minDistance, locationListener);
To track a location in the background, services are used (class Service). Using the service, you can write data to files, and if you have an Internet connection, upload them to the server. Check Internet availability:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { //интернет доступен }