Skip to content

Instantly share code, notes, and snippets.

@VAdaihiep
Last active November 12, 2020 11:15
Show Gist options
  • Save VAdaihiep/1eda782a2728d75c5bd7 to your computer and use it in GitHub Desktop.
Save VAdaihiep/1eda782a2728d75c5bd7 to your computer and use it in GitHub Desktop.
Tracking current location in background in interval. User google play service version 6.1.71. Use with newer google play service will be updated soon. Usage: context.startService(new Intent(context, AutoUpdateLocationService.class)); to start tracking. context.stopService(new Intent(context, AutoUpdateLocationService.class)); to stop tracking.
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationRequest;
public class AutoUpdateLocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
private LocationClient mLocationClient;
private PendingIntent mLocationPendingIntent;
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 2 * 60 * 1000;
public AutoUpdateLocationService() {
}
/*
* Called befor service onStart method is called.All Initialization part
* goes here
*/
@Override
public void onCreate() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Intent intent = new Intent(this, SendLocationService.class);
mLocationPendingIntent = PendingIntent.getService(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mLocationClient = new LocationClient(getApplicationContext(), this,
this);
mLocationClient.connect();
}
/*
* You need to write the code to be executed on service start. Sometime due
* to memory congestion DVM kill the running service but it can be restarted
* when the memory is enough to run the service again.
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*
* Overriden method of the interface
* GooglePlayServicesClient.OnConnectionFailedListener . called when
* connection to the Google Play Service are not able to connect
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects. If the error
* has a resolution, try sending an Intent to start a Google Play
* services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
// If no resolution is available, display a dialog to the user with
// the error.
Log.i("info", "No resolution is available");
}
}
/*
* This is overriden method of interface
* GooglePlayServicesClient.ConnectionCallbacks which is called when
* locationClient is connecte to google service. You can receive GPS reading
* only when this method is called.So request for location updates from this
* method rather than onStart()
*/
@Override
public void onConnected(Bundle arg0) {
Log.i("VAdaihiep", "Location Client is Connected");
// Backgroud update location even app killed by system
mLocationClient.requestLocationUpdates(mLocationRequest,
mLocationPendingIntent);
Log.i("VAdaihiep", "Service Connect status :: " + isServicesConnected());
}
@Override
public void onDisconnected() {
Log.i("VAdaihiep", "Location Client is Disconnected");
}
/**
* Verify that Google Play services is available before making a request.
*
* @return true if Google Play services is available, otherwise false
*/
private boolean isServicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(AutoUpdateLocationService.this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
return false;
}
}
/*
* Called when Sevice running in backgroung is stopped. Remove location
* upadate to stop receiving gps reading
*/
@Override
public void onDestroy() {
Log.i("VAdaihiep", "Service is destroyed");
mLocationClient.removeLocationUpdates(mLocationPendingIntent);
super.onDestroy();
}
}
import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
public class SendLocationService extends IntentService {
public SendLocationService() {
super("LocationIntentService");
}
public SendLocationService(String name) {
super(name);
}
/**
* Called when a new location update is available.
*/
@Override
protected void onHandleIntent(Intent intent) {
Bundle b = intent.getExtras();
Location loc = (Location) b.get(LocationClient.KEY_LOCATION_CHANGED);
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Log.i("VAdaihiep", "Background Latitude: " + latitude);
Log.i("VAdaihiep", "Background Longitude: " + longitude);
Log.i("VAdaihiep", "Accuary: " + loc.getAccuracy() + " m");
sendMyLocation(latitude, longitude);
}
private void sendMyLocation(double lati, double longi) {
// TODO Send location to Server or do somethings like this
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment