Hi, I have a good understanding of location services and how we can use the perfect way in it. Look, I will give you an idea of ββfused apits.
Just follow the instructions below. This is pretty good and simple. Step 1. Make this class GoogleLocationService.java
public class GoogleLocationService { private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks(); LocationUpdateListener locationUpdateListener; Context activity; protected GoogleApiClient mGoogleApiClient; protected LocationRequest mLocationRequest; public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000; public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) { this.locationUpdateListener = locationUpdateListener; this.activity = activity; buildGoogleApiClient(); } protected synchronized void buildGoogleApiClient() { //Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(activity) .addConnectionCallbacks(callbacks) .addOnConnectionFailedListener(callbacks) .addApi(LocationServices.API) .build(); createLocationRequest(); mGoogleApiClient.connect(); } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { @Override public void onConnected(Bundle bundle) { startLocationUpdates(); } @Override public void onConnectionSuspended(int i) { mGoogleApiClient.connect(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) { Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show(); } locationUpdateListener.cannotReceiveLocationUpdates(); } @Override public void onLocationChanged(Location location) { if (location.hasAccuracy()) { if (location.getAccuracy() < 30) { locationUpdateListener.updateLocation(location); } } } } private static boolean locationEnabled(Context context) { boolean gps_enabled = false; LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { ex.printStackTrace(); } return gps_enabled; } private boolean servicesConnected(Context context) { return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context); } private boolean isPackageInstalled(String packagename, Context context) { PackageManager pm = context.getPackageManager(); try { pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); return true; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); return false; } } public void startUpdates() { /* * Connect the client. Don't re-start any requests here; instead, wait * for onResume() */ if (servicesConnected(activity)) { if (locationEnabled(activity)) { locationUpdateListener.canReceiveLocationUpdates(); startLocationUpdates(); } else { locationUpdateListener.cannotReceiveLocationUpdates(); Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show(); } } else { locationUpdateListener.cannotReceiveLocationUpdates(); Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show(); } } //stop location updates public void stopUpdates() { stopLocationUpdates(); } //start location updates private void startLocationUpdates() { if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } if (mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks); } } public void stopLocationUpdates() { if (mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks); } } public void startGoogleApi() { mGoogleApiClient.connect(); } public void closeGoogleApi() { mGoogleApiClient.disconnect(); } }
Step2. Make this interface LocationUpdateListener.java
public interface LocationUpdateListener { void canReceiveLocationUpdates(); void cannotReceiveLocationUpdates(); void updateLocation(Location location); void updateLocationName(String localityName, Location location); }
Step 3. Make this location service class LocationService.java
public class LocationService extends Service { private GoogleLocationService googleLocationService; @Override public void onCreate() { super.onCreate(); //start the handler for getting locations //create component updateLocation(getApplicationContext()); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return Service.START_STICKY; } //get current location os user private void updateLocation(Context context) { googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() { @Override public void canReceiveLocationUpdates() { } @Override public void cannotReceiveLocationUpdates() { } //update location to our servers for tracking purpose @Override public void updateLocation(Location location) { if (location != null ) { Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude()); } } @Override public void updateLocationName(String localityName, Location location) { googleLocationService.stopLocationUpdates(); } }); googleLocationService.startUpdates(); } IBinder mBinder = new LocalBinder(); public class LocalBinder extends Binder { public LocationService getServerInstance() { return LocationService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } //stop location updates on stopping the service @Override public void onDestroy() { super.onDestroy(); if (googleLocationService != null) { googleLocationService.stopLocationUpdates(); } } }
Edited answer:
How to use the service
Start the service in your main action, for example
startService(new Intent(context, LocationService.class));
to stop
stopService(new Intent(context, LocationService.class));
and declare in the manifest as follows:
<service android:name=".service.location.LocationService" android:enabled="true"></service>
Note: I did this because I need a place after you killed the application. If you do not want to work with the service. Then you can call directly below the code in the class where you need to update the location and remove the locationervice.
private GoogleLocationService googleLocationService; googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() { @Override public void canReceiveLocationUpdates() { } @Override public void cannotReceiveLocationUpdates() { } //update location to our servers for tracking purpose @Override public void updateLocation(Location location) { if (location != null ) { Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude()); } } @Override public void updateLocationName(String localityName, Location location) { googleLocationService.stopLocationUpdates(); } }); googleLocationService.startUpdates(); and call this onDestroy if (googleLocationService != null) { googleLocationService.stopLocationUpdates(); }
Remember that Locationservice must also be declared in the manifest. In my opinion, this is the best solution. Thank you for helping this.