Fetch continuous location changes with less battery drainage - android

I want to fetch the user location continuously and update the same in my database.
I am using FusedLocationApi to get the continuous location changes.
To get the location the user has to turn on GPS and Internet connection has to be there.
Keeping the GPS turned for a long time and using INTERNET continuously are the main culprit for battery drainage.
So I want to know what should be done to use the minimum battery power and fetch the continuous location changes.
This is how i am fetching the location,
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();
mGoogleApiClient.connect();
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 .....................");
}
}
}

https://developer.android.com/guide/topics/location/strategies
Google advice creating a model that's will account for best performance. To paraphrase the linked page...
choose the right time to start listening for updates from desired location providers.
Maintain a "current best estimate" of location by filtering out new, but less accurate fixes.
Stop listening for location updates for sometime.
Take advantage of the last best location estimate.
Continuous location changes is a very generic approach to a problem and you need to define the problem and solution to your very specific usecase.

Related

FusedLocationApi not providing the proper location sometimes

I am developing an application that is highly dependent on user location and geo fencing. I am trying to get the user location first and based on that further operations are carried out. Everything is working fine except for the fact that, some times I am getting wrong location values and unless and until I restart the app and in some cases, restart the phone, I don't get the correct value. I will post my Location Api codes below. If any changes required, please do let me know.
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
buildGoogleApiClient();
if (!statusOfGPS) {
displayPromptForEnablingGPS(this);
} else {
permissionAndLocationAccess();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Update location every second
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
} else {
ProgressUtil.hideProgressDialog(prgd_progressDialog);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();
Log.e("Lat and Lng", "onconn");
if (!String.valueOf(lat).equals("0.0")) {
latitudeVal = mLastLocation.getLatitude();
longitudeVal = mLastLocation.getLongitude();
sendLatLong(latitudeVal, longitudeVal);
Log.d("Lat and Lng", "in last loc");
Log.d("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);
new AsyncCaller().execute();
}
}
}
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
Log.e("Lat and Lng", "onchanged");
if (!String.valueOf(lat).equals("0.0")) {
latitudeVal = location.getLatitude();
longitudeVal = location.getLongitude();
ProgressUtil.hideProgressDialog(prgd_progressDialog);
Log.e("Lat and Lng", "onchanged0");
Log.e("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);
I am also using this class and in my case its working fine. You can check
public class BackgroundLocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
protected static final String TAG = "BackService";
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = GLOBAL_BACKGROUND_CHECK_TIME;
public GoogleApiClient mGoogleApiClient;
public LocationRequest mLocationRequest;
private PendingIntent mPendingIntent;
IBinder mBinder = new LocalBinder();
private class LocalBinder extends Binder {
public BackgroundLocationService getServerInstance() {
return BackgroundLocationService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate()");
Intent mIntentService = new Intent(this, LocationUpdates.class);
mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
buildGoogleApiClient();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (mGoogleApiClient.isConnected()) {
Log.i(TAG + " onStartCmd", "Connected");
return START_STICKY;
}
if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
Log.i(TAG + " onStartCmd", "GoogleApiClient not Connected");
mGoogleApiClient.connect();
}
NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
notification.setContentTitle("Title ");
notification.setContentText("\n Tracking BackGround ... ");
notification.setSmallIcon(R.drawable.big_marker);
notificationManager.notify(151458461, notification.build());
return START_STICKY;
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
createLocationRequest();
}
protected void createLocationRequest() {
Log.i(TAG, "createLocationRequest()");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(GLOBAL_BACKGROUND_CHECK_TIME);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
Log.i(TAG, "Started Location Updates");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
}
public void stopLocationUpdates() {
Log.i(TAG, "Stopped Location Updates");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mPendingIntent);
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
startLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
String message = "Latitude : " + location.getLatitude() + "\n Longitude : " + location.getLongitude() +
"\n location Accuracy: " + location.getAccuracy() + "\n speed: " + location.getSpeed();
Log.d(TAG, "onLocationChanged: " + message);
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
#Override
public void onDestroy() {
super.onDestroy();
stopLocationUpdates();
}
}

Getting GPS location in my Android Wearable in China

I am developing an Android app for a smartwatch that was bought and it's running in China.
My goal is to get the GPS location of the device and track its movement, but I cannot seem to find how to make it work.
Currently, I'm developing for API 21 and I'm using the following library of Google Play Services, as it is the one used by Wearables in China: com.google.android.gms:play-services-wearable:7.8.87
The code that I am using is the following:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_route);
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL_MS)
.setFastestInterval(FASTEST_INTERVAL_MS);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addApi(Wearable.API) // used for data layer API
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
startTravelTime = System.currentTimeMillis();
if (!hasGps()) {
Log.d(TAG, "This hardware doesn't have GPS.");
}
}
private boolean hasGps() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS);
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
Log.i("Connected!!!", "WERE CONNECTED");
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
mGoogleApiClient.disconnect();
System.out.println("onstop");
}
#Override
protected void onResume() {
super.onResume();
if(!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, OnRouteActivity.this);
}
mGoogleApiClient.disconnect();
}
#Override
public void onConnected(Bundle bundle) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.getStatus().isSuccess()) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Successfully requested location updates");
}
} else {
Log.e(TAG,
"Failed in requesting location updates, "
+ "status code: "
+ status.getStatusCode()
+ ", message: "
+ status.getStatusMessage());
}
}
});
}
#Override
public void onLocationChanged(Location location){
// Display the latitude and longitude in the UI
mTextView = (TextView) findViewById(R.id.location);
mTextView.setText("Latitude: " + String.valueOf( location.getLatitude()) + "\nLongitude: " + String.valueOf( location.getLongitude()));
Toast.makeText(getBaseContext(), "Latitude: " + String.valueOf( location.getLatitude()) + "\nLongitude: " + String.valueOf( location.getLongitude()), Toast.LENGTH_LONG).show();
}
I hope someone can help me with this :)
For location to work on Chinese wearable devices you should use the Fused Location Provider API and make sure to include the following line in your build.gradle file:
dependencies {
...
compile 'com.google.android.gms:play-services-location:10.2.0'
}
In addition to the above you also need to add:
dependencies {
...
compile 'com.google.android.gms:play-services-wearable:10.2.0'
}
More details can be found in Google's guide Creating Android Wear Apps for China

Fused Location Provider issues

I am using Fused Location Api for getting the latitude and longitude.It's mentioned in the documents that it uses GPS, Wifi and network(Cell) to return the most accurate location of the user. I've a couple of questions here:
1)I've noticed that if I turn off the wifi, it still gives the result but it gives null when GPS is turned off, why is that? Isn't it suppose to use the Wifi to give the location detail even if gps is off or not available? P.S. I've used ACCESS_FINE_LOCATION for permission.
2)How can I know/test whether the location detail is returned using Wifi or GPS or network (Cell tower)?
3)Will it work using network (cell tower) when both GPS and wifi are off?
Fused Location Provider code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblLocation = (TextView) findViewById(R.id.lblLocation);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
if (checkPlayServices()) {
Log.i("playservice", checkPlayServices()+"");
// Building the GoogleApi client
buildGoogleApiClient();
}
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
}
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longitude);
} else {
lblLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "GoogleApiClient connected!");
createLocationRequest();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.i(TAG, " Location: " + mLastLocation);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationCallback() {
#Override
public void onLocationResult(final LocationResult locationResult) {
Log.i("onLocationResult",locationResult + "");
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lblLocation.setText(locationResult.getLocations() + "");
}
});
}
#Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
Log.i("onLocationAvailability", "onLocationAvailability: isLocationAvailable = " + locationAvailability.isLocationAvailable());
}
}, null);
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
Log.i(TAG, "mGoogleApiClient.connect()");
}
}
When I've GPS on, the output I get is:
I/onLocationResult(7481): LocationResult[locations: [Location[fused 27.673576,85.314083 acc=16 et=+1d1h59m30s347ms alt=1289.0999755859375 vel=0.93 bear=166.0]]]

OnLocationChanged CallBacked Never Get Called While Using Google Map Android?

Hello Guys This may be asked many many times but i couldn't find any solution from that so am making this post let me explain my problem i have simple google map application in that onlocationchanged callback never get called don't know where am making mistake let me post the code:
public class VisitTravel extends AppCompatActivity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
OnMapReadyCallback,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
GoogleMap mGoogleMap;
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);
setContentView(R.layout.activity_visit_travel);
if (!isGooglePlayServicesAvailable()) {
finish();
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
createLocationRequest();
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
/// tvLocation = (TextView) findViewById(R.id.tvLocation);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#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());
Location mLastLocations = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
Log.d("insideready","ready");
if (mLastLocations != null) {
LatLng latLng = new LatLng(mLastLocations.getLatitude(), mLastLocations.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
latLng, 12);
mGoogleMap.animateCamera(cameraUpdate);}
else {
startLocationUpdates();
}
}
protected 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
Toast.makeText(this, "LocationNotUpdated", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(VisitTravel.this,
new String[]{android.Manifest.permission
.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
20);
} else {
if (mGoogleApiClient.isConnected()) {
createLocationRequest();
Log.e("locupdate","connected");
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
// Toast.makeText(this, "LocationUpdatedStart", Toast.LENGTH_SHORT).show();
}
}
}
#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();
}
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 .....................");
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setMyLocationEnabled(true);
}
}
In this on LocationChanged never getting called can anyone help me and for addition information am having background service which used to fetch location for every certain time in that i have separate instance of google api client is that affecting this one ? Thanks in advance

Android : Continuous Location update

I am a newbie to Android and working on my very first application. I am working on a application which takes continuous location update and show that on google map. It means no matter whether application is in foreground or in background.
For the same I am using fusedlocation API's requestLocationUpdates. There are two version of the same viz:
With LocationListener when app is in foreground
With pendingIntent when app goes to background.
So as per my understanding I have to use both as I need continuous update.So I am using both in my application as I need continuous update.
But as a surprise I got that requestLocationUpdates with pendingIntent giving me location update in foreground as well. So I am very confused here and sometime giving Location as NULL .
Please tell me what is the exact behaviour of requestLocationUpdates with pendingIntent . Will it work for both foreground and bckground ? If yes then why I am getting the Location as NULL sometime.
Another problem when I was using Locationreveiver then I was able toget proper location update when app was in foreground and I was drawing a line on googlemap. But I noticed my line was not in sync with googlemap route. It was zig zag . So here I am confused If I am getting continuous update then why not m route is sync with google route .
I am attaching the complecode of my location class. Please help
public class LocationMapsActivity extends FragmentActivity implements
LocationListener,
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
ComponentCallbacks2,
GoogleApiClient.OnConnectionFailedListener {
//*******************************member variables*********************************************
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 *02; // 1000*60*1 = 1 minute
private static final long FASTEST_INTERVAL = 1000 *01 ;// 10 sec
public static LatLng mPrev = null;
private double mCurrentDistance = 0;
private double mTotalDistance = 0;
private double mCurrentSpeed = 0;
public static String stateOfLifeCycle = "";
public static boolean wasInBackground = false;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
Location mStartLocation;
GoogleMap googleMap;
//********************************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate ...............................");
wasInBackground = false;
stateOfLifeCycle = "Create";
//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_map_location);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
//*******************ComponentCallbacks2*************************
#Override
public void onTrimMemory(int level) {
if (stateOfLifeCycle.equals("Stop")) {
wasInBackground = true;
}
super.onTrimMemory(level);
Toast.makeText(getApplicationContext(),
"Application OnTrimmemory ", Toast.LENGTH_SHORT)
.show();
}
//****************Activity****************************
#Override
public void onStart() {
Toast.makeText(getApplicationContext(),"OnStart ", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onStart fired ..............");
stateOfLifeCycle = "Start";
if (wasInBackground) {
Toast.makeText(getApplicationContext(),"Application came to foreground",Toast.LENGTH_SHORT).show();
wasInBackground = false;
}
super.onStart();
if(!mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
}
//********************Activity************************
#Override
public void onStop() {
stateOfLifeCycle = "Stop";
Log.d(TAG, "onStop fired ..............");
stopLocationUpdates();
// mGoogleApiClient.disconnect();
super.onStop();
Toast.makeText(getApplicationContext(), "OnStop ", Toast.LENGTH_SHORT).show();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
//**************Activity******************************
#Override
protected void onPause() {
stateOfLifeCycle = "Pause";
super.onPause();
Toast.makeText(getApplicationContext(), "OnPause ", Toast.LENGTH_SHORT) .show();
}
//*******************Activity*************************
#Override
public void onResume() {
Toast.makeText(getApplicationContext(),"OnResume ", Toast.LENGTH_SHORT).show();
stateOfLifeCycle = "Resume";
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
//*****************Activity***************************
#Override
public void onDestroy()
{
wasInBackground = false;
stateOfLifeCycle = "Destroy";
super.onDestroy();
Toast.makeText(getApplicationContext(), "Application OnDestroy ", Toast.LENGTH_SHORT).show();
}
//******************OnMapReadyCallback**************************
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
//googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
//*******************GoogleApiClient.ConnectionCallbacks*************************
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
//*******************GoogleApiClient.ConnectionCallbacks*************************
#Override
public void onConnectionSuspended(int i) {
}
//*****************GoogleApiClient.ConnectionCallbacks***************************
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
//*****************LocationListener***************************
// #Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
LatLng current = new LatLng(location.getLatitude(), location.getLongitude());
if(mPrev == null) //when the first update comes, we have no previous points,hence this
{
mPrev=current;
mStartLocation = location;
addMarker();
}
else {
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(current, 17);
googleMap.animateCamera(update);
PolylineOptions pOptions = new PolylineOptions()
.width(7)
.color(Color.BLUE)
.visible(true);// .geodesic(true)
pOptions.add(mPrev);
pOptions.add(current);
googleMap.addPolyline(pOptions);
mPrev = current;
current = null;
}
}
//********************************************
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
//********************************************
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
Log.d(TAG, "isGooglePlayServicesAvailable ...............: SUCCESS" );
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
//********************************************
protected void startLocationUpdates() {
//Get foreground location update
/* PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);*/
//Get background location update
String proximitys = "ACTION";
IntentFilter filter = new IntentFilter(proximitys);
getApplicationContext().registerReceiver(new LocationReceiver() , filter);
Intent intent = new Intent(proximitys);
// Intent intent = new Intent(this, LocationReceiver.class);
PendingIntent locationIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationIntent);
}
//********************************************
public void HandleLocationChanged(Location location) {
Log.d(TAG, "Firing HandleLocationChanged..............................................");
// Toast.makeText(getApplicationContext(), "HandleLocationChanged", Toast.LENGTH_LONG).show();
if(location == null)
{
Toast.makeText(getApplicationContext(), "location is null", Toast.LENGTH_LONG).show();
return;
}
mCurrentLocation = location;
LatLng current = new LatLng(location.getLatitude(), location.getLongitude());
if(mPrev == null) //when the first update comes, we have no previous points,hence this
{
mPrev=current;
mStartLocation = location;
addMarker();
}
else {
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(current, 17);
googleMap.animateCamera(update);
PolylineOptions pOptions = new PolylineOptions()
.width(7)
.color(Color.BLUE)
.visible(true);// .geodesic(true)
pOptions.add(mPrev);
pOptions.add(current);
googleMap.addPolyline(pOptions);
mPrev = current;
current = null;
}
}
//********************************************
public String getAddress( )
{
Geocoder geocoder = new Geocoder(this);
String addressLineTemp=null;
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(), 1);
if (addresses.size() > 0) {
addressLineTemp = addresses.get(0).getAddressLine(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return addressLineTemp;
}
//********************************************
private void addMarker() {
MarkerOptions options = new MarkerOptions();
LatLng currentLatLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
options.position(currentLatLng);
Marker mapMarker = googleMap.addMarker(options);
mapMarker.setTitle(getAddress());
Log.d(TAG, "Marker added.............................");
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng,
13));
Log.d(TAG, "Zoom done.............................");
}
//********************************************
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
//********************************************
public class LocationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "Firing LocationReceiver....onReceive..........................................");
Location location = (Location) intent.getExtras().get(LocationServices.FusedLocationApi.KEY_LOCATION_CHANGED);
HandleLocationChanged(location);
}
}

Categories

Resources