I am working on a Location-App which should begin to track some statistic data based on longitude and latitude when the user presses a Button. All this stuff works very well but when it comes to lock the screen or put the app in the background the service does not work anymore !
I have read a lot about background services and Broadcast receivers but I don't know how to implement the Google API Location listener in a Service and where to implement this class in the MainActivity. Can anyone tell me with a short code example how to implement such a service or a link where this is explained ?
Use fuse location service and save updated location every time
public class LocationNotifyService extends Service implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
public static Location mCurrentLocation;
.............................
#Override
public void onCreate() {
//show error dialog if GoolglePlayServices not available
if (isGooglePlayServicesAvailable()) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(BACKGROUND_INTERVAL);
mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//mLocationRequest.setSmallestDisplacement(10.0f); /* min dist for location change, here it is 10 meter */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
//Check Google play is available or not
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
return ConnectionResult.SUCCESS == status;
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
try {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} catch (IllegalStateException e) {}
}
#Override
public void onLocationChanged(Location location) {
//Save your location
}
............................
}
you can get current location onLocationChanged()
For more details check http://javapapers.com/android/android-location-fused-provider/ or follow official guide https://developer.android.com/training/location/index.html
Here is application that does something like you want:
https://github.com/sergstetsuk/CosyDVR/blob/master/src/es/esy/CosyDVR/CosyDVR.java
Main Activity starts on BackgroundVideoRecorder service.
Intent intent = new Intent(/*CosyDVR.this*/getApplicationContext(), BackgroundVideoRecorder.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
look at mConnection onServiceConnected,onServiceDisconnected.
Here is BackgroundVideoRecorder class:
https://github.com/sergstetsuk/CosyDVR/blob/master/src/es/esy/CosyDVR/BackgroundVideoRecorder.java
It implements LocationListener. So has onLocationChanged, onProviderDisabled, onProviderEnabled, onStatusChanged.
Related
i am making an android application. I want to stop location updates if the device is still and if it moves a distance of 300 or 400m then get it's location again. I don't want to check continuously for location updates and measure distance between previous location and current location because it consumes battery.
My Location service class code:
public class LocationService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
}
#Override
public void onCreate() {
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
public void buildGoogleApiClient() {
createLocationRequest();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(500);
}
public void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
buildGoogleApiClient();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
// The service is no longer used and is being destroyed
stopLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
System.out.println("Latitude: " + location.getLatitude());
System.out.println("Longitude: " + location.getLongitude());
}
#Override
public void onConnected(#Nullable Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
I am using locationRequest.setSmallestDisplacement(500) but it continuously receives location updates only the onLocationChanged method is not called if the distance between previous and current location is less than 500m e.g.
Should i use geofencing for this purpose?
What is the best possible way to achieve this using FusedLocationApi with minimum battery consumption?
There are a few things to note here:
When your device isn't moving, Location Services optimizes for battery and does not necessarily do expensive new location lookups. So, you don't really have to try to optimize for this yourself.
Consider passing a smaller value to LocationRequest#setSmallestDisplacement.
To optimize for battery, consider using batched location updates, where location is computed for you in at the interval described in LocationRequest#setInterval, but delivered to your device based on the value in LocationRequest#setMaxWaitTime. This greatly helps with battery.
Not part of your question, but I should note that I would structure the code for requesting and removing location updates a little differently. I would connect GoogleApiClient in onStart(), and disconnect it in onStop(). I would call requestLocationUpdates() in onResume() of in onConnected(), and call removeLocationUpdates() in onPause() or onStop(), but not as late as onDestroy().
So, I have a JobService that is being called on background. However I need it to get the current location and send it to the webservice. The webservice is working great when I send static data. However getting the location is being a problem. The location object is always null. This is what I've been trying.
public class GPSBackgroundJobService extends JobService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private String LOGSERVICE = "GPS";
private InspectorsLogic mInspectorsLogic;
ParsoContext mContext;
private GoogleApiClient mGoogleApiClient;
ParsoLocationListener mLocationListener;
Location mLastLocation;
Double longitude;
Double latitude;
#Override
public void onCreate() {
super.onCreate();
Log.i(LOGSERVICE, "onCreate");
mContext = (ParsoContext) getApplicationContext();
mInspectorsLogic = new InspectorsLogic(mContext);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
#Override
public boolean onStartJob(JobParameters job) {
Log.i(LOGSERVICE, "onStartJob called");
mGoogleApiClient.connect();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation!=null) {
latitude = mLastLocation.getLatitude();
longitude =mLastLocation.getLongitude();
sendGPSTask mSendGPSTask = new sendGPSTask();
mSendGPSTask.execute(Double.toString(latitude), Double.toString(longitude));
}else{
Log.e(LOGSERVICE, "Lat and Long are null");
}
return false;
}
#Override
public boolean onStopJob(JobParameters job) {
mGoogleApiClient.disconnect();
return false;
}
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
getLastLocation returns null if it doesn't have a location fix yet- which means unless you're using GPS elsewhere, it almost always returns null. To make sure you get a location use getLocationUpdates and wait for the location to fix (this will not be instant, depending on atmospheric conditions, whether you're inside or out, etc this could take a few seconds to a minute or so- or just never happen).
Apparently the code is fine, to make it work this is what I did:
check the permissions of the app (the location one needs to be activated)
change your GPS settings to (mobile data and wifi one)
making this with the current code posted on the question, made it.
I am trying to create a service that will receive location updates every x sec and after y distance. I receive updates after x sec but never after y distance. I have tested it multiple times with different values and it seems that setSmallestDisplacement is not working at all. There have been various posts about that matter but without any solution. I would appreciate it if someone could help me or even point me to a different direction.
My Service
public class GPS_Service extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private int timethresh;
private int distancethresh;
protected Location mCurrentLocation;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//Set the desired interval for active location updates, in milliseconds.
mLocationRequest.setInterval(60* 1000);
//Explicitly set the fastest interval for location updates, in milliseconds.
mLocationRequest.setFastestInterval(30* 1000);
//Set the minimum displacement between location updates in meters
mLocationRequest.setSmallestDisplacement(1); // float
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onConnected(Bundle bundle) {
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
//Requests location updates from the FusedLocationApi.
startLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
//Toast.makeText(this, ""+mCurrentLocation.getLatitude()+","+mCurrentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
System.out.println(""+mCurrentLocation.getLatitude()+","+mCurrentLocation.getLongitude());
}
#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.
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(getApplicationContext(),"Location services connection failed with code " + connectionResult.getErrorCode(), Toast.LENGTH_LONG).show();
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
According to this SO question especially the answer of cgr.
The Displacement that is set for LocationRequest, has no chance of getting the locations if device is still as Displacement takes precedance over Intevals (interval and fastestInterval). As I could guess - Maybe you have passed different LocationRequest object (with no displacement set) to LocationServices.FusedLocationApi.requestLocationUpdates().
The LocationRequest setSmallestDisplacement (float
smallestDisplacementMeters)
is set the minimum displacement between location update in meters. By default the value of this is 0. It returns the same object, so that the setters can be chained.
NOTE: Location requests from applications with ACCESS_COARSE_LOCATION
and not ACCESS_FINE_LOCATION will be automatically throttled to a
slower interval, and the location object will be obfuscated to only
show a coarse level of accuracy.
Check this page for more information.
Try something like this:
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(100); //100 meters
}
I am using google location api for fetching location. issue I'm facing is when the user turned the GPS off I'm not getting the Lcoation, as per this post says we can access Network based location even-though the GPS is turned off. but I'm not getting locaton when the user turned off the location access.
this is my service to fetch location
public class LocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener, ResultCallback<Status> {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startLocationUpdates();
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
LogUtils.LOGI(TAG, "Service created");
buildGoogleApiClient();
setupBroadCastListenerForGpsStatusChange();
initLastLocationDetails();
}
/**
* Requests location updates from the FusedLocationApi.
*/
protected void startLocationUpdates() {
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
} else {
mRequestingLocationUpdates = true;
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
/**
* Builds a GoogleApiClient. Uses the {#code #addApi} method to request the
* LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
LogUtils.LOGI(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(ActivityRecognition.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setSmallestDisplacement(SMALLEST_DISTANCE_METERS);
}
#Override
public void onConnected(Bundle connectionHint) {
startLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
//location operations
}
}
So my question is, Is it really possible to access location when the location access is disabled (not last cached location), if yes, what is wrong with my code
if (isNetworkEnabled) {
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BTWN_UPDATES,
DISTANCE_OF_UPDAPTES, this);
if (manager != null) {
location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
You canot start the service natively using just Google Api Location , you should manage to operate the location based on user request by using boolean location manager. Otherwise your attempts dose not look superficial, you can either use get when gps is on or off depending when detected.
I am trying to create a route tracking app. it need to track location even if the app is in background. so i created a service and add code to this service. Following are my code. but there is one problem. I start the service from my main activity.
public void startTracking(View view) {
startService(new Intent(MainActivity.this, LocationIntentService.class));
}
public void stopTracking(View view) {
stopService(new Intent(MainActivity.this, LocationIntentService.class));
}
It start the service and locations are inserted to a local db. But i cant stop these service. When i stop service using above code it still track the location. How can i stop location update.
public class LocationIntentService extends IntentService implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = LocationIntentService.class.getSimpleName();
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
private static int DISPLACEMENT = 10;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
DBAdapter dbAdapter;
public LocationIntentService() {
super("LocationIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.e(TAG, " ***** Service on handled");
if (isGooglePlayServicesAvailable()) {
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
#Override
public void onConnected(Bundle bundle) {
Log.e(TAG, " ***** Service on connected");
startLocationUpdates();
openDB();
}
#Override
public void onConnectionSuspended(int i) {
Log.e(TAG, " ***** Service on suspended");
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "Location changed");
mLastLocation = location;
String latitude = String.valueOf(mLastLocation.getLatitude());
String longitude = String.valueOf(mLastLocation.getLongitude());
Log.e(TAG, " ##### Got new location"+ latitude+ longitude);
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
String timestamp = today.format("%Y-%m-%d %H:%M:%S");
dbAdapter.insertRow(latitude, longitude, timestamp);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ connectionResult.getErrorCode());
}
#Override
public void onDestroy() {
Log.e(TAG, "Service is Destroying...");
super.onDestroy();
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
mGoogleApiClient.disconnect();
}
closeDB();
}
protected void stopLocationUpdates() {
Log.d(TAG, "Location update stoping...");
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
protected void startLocationUpdates() {
Log.d(TAG, "Location update starting...");
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
private void openDB() {
dbAdapter = new DBAdapter(this);
dbAdapter.open();
}
private void closeDB() {
dbAdapter = new DBAdapter(this);
dbAdapter.close();
}
protected void createLocationRequest() {
Log.e(TAG, " ***** Creating location request");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
Log.e(TAG, " ***** Update google play service ");
return false;
}
}
}
The reason that it's not working for you is that you are using an IntentService, so calling stopService() will not cause onDestroy() to be called, presumably because it was already called after onHandleIntent() has completed. There is no need to ever call stopService() on an IntentService see here.
It looks like you should probably just use Service instead of IntentService. That way, when you call stopService(), it would call onDestroy() and unregister for location updates, as you expect.
The only other change you would need to make would be to override onStartCommand() instead of onHandleIntent().
You would have your class extend Service instead of IntentService, and then move your code to register for location updates to onStartCommand:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, " ***** Service on start command");
if (isGooglePlayServicesAvailable()) {
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
return Service.START_STICKY;
}
This way you can still call startService() and stopService(), and it should work as you are expecting.
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
call stopLocationUpdates() method in stopService()
When you stop your services. Then called this line in LocationIntentService.class.
locationManager.removeUpdates(this);