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);
}
}
Related
i am try to show current updated location on map.
when i zoom in on map and location updated then it zoom out and then show location. it does not show updated location on same zoom position.
when location update then i am again set marker on map. i think problem in setting marker on map . please help me in showing current updated location on
map.
public class MainActivity extends FragmentActivity implements OnMapReadyCallback , GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
GoogleMap googleMa;
double latitude;
private GoogleApiClient mGoogleApiClient;
double longitude;
private Location mLastLocation = null;
private LocationRequest mLocationRequest;
String mPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
protected LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
2);
locationManager = (LocationManager) MainActivity.this
.getSystemService(Context.LOCATION_SERVICE);
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
initailizeMap();
}
public void initailizeMap() {
if (googleMa == null) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
googleMa = googleMap;
Log.d("aaaaaa", " on map --->" + latitude + " " + longitude);
displayLocation();
}
public void displayLocation() {
try {
GPSTracker gps = new GPSTracker(MainActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Latitude: " + latitude + " Longitude: " + longitude, Toast.LENGTH_LONG).show();
final LatLng loc = new LatLng(latitude, longitude);
Marker ham = googleMa.addMarker(new MarkerOptions().position(loc).title("This is Me").icon(BitmapDescriptorFactory.fromResource(R.drawable.greenpointer)));
googleMa.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
}
} catch (Exception e) {
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i("aaaaaaaa", "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
Log.d("aaaaaaaa===>", "" + String.valueOf(location.getLatitude()) + "\n" + String.valueOf(location.getLongitude()));
Toast.makeText(getApplicationContext(), "Location changed!",
Toast.LENGTH_SHORT).show();
displayLocation();
}
private boolean checkPlayServices() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (googleApiAvailability.isUserResolvableError(resultCode)) {
googleApiAvailability.getErrorDialog(this, resultCode,
1000).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(100);
mLocationRequest.setFastestInterval(500);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(MainActivity.this, 2000);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000); // 10 sec
mLocationRequest.setFastestInterval(5000); // 5 sec
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(10); // 10 meters
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
protected void onDestroy() {
super.onDestroy();
stopLocationUpdates();
}
}
After the onLocationChanged is triggered then you need to fetch latitude and longitude from location instance not from gps (i don't know what GPSTracker is,no code but surely it's not giving you updated lat,long)
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
// use latitude and longitude given by
// location.getLatitude(), location.getLongitude()
// for updated location marker
Log.d("aaaaaaaa===>", "" + location.getLatitude() + "\n" + location.getLongitude());
// displayLocation();
// to remove old markers
googleMa.clear();
final LatLng loc = new LatLng(location.getLongitude(), location.getLongitude());
Marker ham = googleMa.addMarker(new MarkerOptions().position(loc).title("This is Me").icon(BitmapDescriptorFactory.fromResource(R.drawable.greenpointer)));
googleMa.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
}
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
I am new in android I want to run a service in background and get latitude and longitude or Geo address after 10 minutes and send to the server.
Please help me.
Here is my code:
In Activity
public void serviceCall(){
Log.e("INSIDE ALARM", "INSIDE ALARM");
Intent intent = new Intent(getApplicationContext(), MyService.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyService.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
long firstMillis = System.currentTimeMillis();
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
6000, pIntent);
}
in Reciver
public static final int REQUEST_CODE = 9411;
#Override
public void onReceive(Context context, Intent intent) {
Intent inti = new Intent(context, LocationService.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(inti);
}
in IntentService
protected void onHandleIntent(Intent intent) {
Log.e("imsidehandler Service", ":=");
mRequestingLocationUpdates = false;
buildGoogleApiClient();
createLocationRequest();
buildLocationSettingsRequest();
checkLocationSettings();
sendDataServer();
}
public void onConnected(Bundle bundle) {
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateLocationUI();
}
}
public void onConnectionSuspended(int i) {
}
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
private void buildLocationSettingsRequest() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
}
private void checkLocationSettings() {
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
mLocationSettingsRequest
);
result.setResultCallback(this);
}
protected boolean 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) {
return true;
}
return false;
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
mRequestingLocationUpdates = false;
}
});
}
private void updateLocationUI() {
if (mCurrentLocation != null) {
updateCityAndPincode(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
}
}
private void updateCityAndPincode(double latitude, double longitude) {
try {
Log.e("latitude","==>"+longitude);
Log.e("longitude","==>"+longitude);
this.latitude = latitude;
this.longitude = longitude;
getGeoAddress(latitude, longitude);
} catch (Exception e) {
}
}
private void getGeoAddress(Double latitude, Double longitude) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
String result = null;
List<Address> addressList = null;
try {
addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
Log.e("address","==>"+address);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
result += address.getAddressLine(i);
result += " ";
}
if (result.contains("null")) {
result1 = result.replace("null", "");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
startLocationUpdates();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult((Activity) getApplicationContext(), REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
please help me
The getLastLocation() method just gets the last known location that the device happens to know. Sometimes the device does not "happen to know" its location and null is returned.
The device doesn't determine its location on its own, but only when some application request the location. So your app is now dependent on other applications requesting location updates.
Also the "last known location" here means exactly that: It may not be up-to-date. Locations do come with a time stamp which could be used to asses if the location might still be relevant.
I don't see a call to requestLocationUpdates() anywhere in your code. That would request up-to-date location updates at an interval which you can specify.
Your onConnected() method could have:
public void onConnected(Bundle bundle) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
(The getLastLocation() call can be deleted.)
And your IntentService could implement LocationListener and do the same things as onConnected() now does, but only after a location update has arrived:
#Override
public void onLocationChanged(Location location) {
// Cancel the updates after the first one:
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateLocationUI();
}
This would be the way to request and process location updates with the smallest code changes.
Of course there are also other ways like requesting the updates every 10 minutes and processing them via a PendingIntent. There's this version of requestLocationUpdates() that takes a PendingIntent:
public abstract PendingResult<Status> requestLocationUpdates (GoogleApiClient client, LocationRequest request, PendingIntent callbackIntent)
That would replace your current timer mechanism.
all i am trying to get the location of the device but it always returns null. I know for the first time it will return null but again and again it is returning null. Below is my code. Please help me to solve this .
public class LocationHelper implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationService";
private static final long INTERVAL = 1000 * 5;
private static final long FASTEST_INTERVAL = 1000 * 3;
Context context;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
LocationUpdateListener locationUpdateListener;
public LocationHelper(Context context, LocationUpdateListener locationUpdateListener) {
this.context = context;
this.locationUpdateListener = locationUpdateListener;
if (!isGooglePlayServicesAvailable()) {
} else {
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
/**
* Create the location request
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
if (ConnectionResult.SUCCESS == status) {
return true;
}else if(status == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED){
Log.d(TAG, "please udpate your google play service");
Log.d(TAG, "please udpate your google play service");
Log.d(TAG, "please udpate your google play service");
return true;
}else {
// GooglePlayServicesUtil.getErrorDialog(status, getBaseContext(), 0).show();
Log.d(TAG, "google play services is not available - ...............:");
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
private void startLocationUpdates() {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.d(TAG, "Location update started ..............: ");
fetchLocation();
Log.d(TAG, "Location update started ..............: ");
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
fetchLocation();
Log.v("onLocationChanged","onLocationChanged");
Log.v("onLocationChanged","onLocationChanged");
Log.v("onLocationChanged","onLocationChanged");
}
//Get the location
private void fetchLocation(){
while (mCurrentLocation == null) {
try {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d(TAG, "Location null ");
Thread.sleep(2000);
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (mCurrentLocation != null) {
locationUpdateListener.locationUpdate(mCurrentLocation);
}
}
}
Thanks in advance
It seems, that you try to get last location when your LocationClient connected. But you need to request a location update to receive your current location instead of calling getLastLocation(). You created your own LocationRequest in createLocationRequest() method but you haven't ever used it in code.
Example code:
LocationServices.FusedLocationApi.requestLocationUpdates(yourGoogleApiClient, yourLocationRequest, yourLocationListener);
Update:
End when you received new location in yourLocationListener you need to you have to stop receiving location updates:
private LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.v("onLocationChanged","onLocationChanged");
if(mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
mGoogleApiClient.disconnect();
}
//your code here }
};
More details you can find here.
Hope it will help you.
I'm looking to create an app in android that basically tracks a phones location and periodically adds a marker to the google maps api so that a route can be displayed, the problem I have is that I don't know how to get the location periodically and in the background.
Here is my code:
public class MapsActivity extends FragmentActivity implements LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
Button btnCurrent, btnPrevious;
ArrayList<Double> latitude = new ArrayList<>();
ArrayList<Double> longitude = new ArrayList<>();
LocationManager lm;
LocationListener ll;
Location networkLocation;
Location gpsLocation;
double LONG;
double LAT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
networkLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 10, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
LONG = networkLocation.getLongitude();
LAT = networkLocation.getLatitude();
latitude.add(LAT);
longitude.add(LONG);
Log.d("COORDS", LAT+" , "+LONG);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
setUpMapIfNeeded();
btnCurrent = (Button)findViewById(R.id.btn_currentLoc);
btnPrevious = (Button) findViewById(R.id.btn_prevLoc);
btnCurrent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mMap.clear();
double curLong, curLat;
String test = lm.getAllProviders().toString();
LatLng CurrentLoc;
Log.d("PROVIDERS ", test);
if((lm.isProviderEnabled("gps"))==true)
{
curLong = gpsLocation.getLongitude();
curLat = gpsLocation.getLatitude();
CurrentLoc = new LatLng(curLat,curLong);
Log.d("GPS", "true");
}else
{
curLong = networkLocation.getLongitude();
curLat = networkLocation.getLatitude();
CurrentLoc = new LatLng(curLat,curLong);
Log.d("GPS", "false");
}
mMap.addMarker(new MarkerOptions().position(new LatLng(curLat,curLong)).title("LOCATION "+ curLat + ", " + curLong));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CurrentLoc,15));
Log.d("LOCATION", curLat + "," + curLong);
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0;i<latitude.size();i++)
{
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude.get(i),longitude.get(i))).title("LOCATION "+ latitude.get(i) + ", " + longitude.get(i)));
Log.d("LOCATION", latitude.get(i)+ "," + longitude.get(i));
}
}
});
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
}
private void getCurrentLocation(){
}
private void seeAllLocations(){
}
#Override
public void onLocationChanged(Location location) {
}
}
Any help would be appreciated.
Check this below code which helps you to get current location on button click and also #some timeInterval.
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
private static int DISPLACEMENT = 10; // 10 meters
// UI elements
private TextView lblLocation;
private Button btnShowLocation, btnStartLocationUpdates;
#Override
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);
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
// Show location button click listener
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
// Toggling the periodic location updates
btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
togglePeriodicLocationUpdates();
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
// Resuming the periodic location updates
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
/**
* Method to display the location on UI
* */
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)");
}
}
/**
* Method to toggle periodic location updates
* */
private void togglePeriodicLocationUpdates() {
if (!mRequestingLocationUpdates) {
// Changing the button text
btnStartLocationUpdates
.setText(getString(R.string.btn_stop_location_updates));
mRequestingLocationUpdates = true;
// Starting the location updates
startLocationUpdates();
Log.d(TAG, "Periodic location updates started!");
} else {
// Changing the button text
btnStartLocationUpdates
.setText(getString(R.string.btn_start_location_updates));
mRequestingLocationUpdates = false;
// Stopping the location updates
stopLocationUpdates();
Log.d(TAG, "Periodic location updates stopped!");
}
}
/**
* Creating google api client object
* */
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Creating location request object
* */
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
/**
* Method to verify google play services on the device
* */
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;
}
/**
* Starting the location updates
* */
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
Toast.makeText(getApplicationContext(), "Location changed!",
Toast.LENGTH_SHORT).show();
// Displaying the new location on UI
displayLocation();
}
}