This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Everytime I want to start the map activity, it crashed and then I got this error in Sentry
Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
Here is the activity :
package something;
import android.*;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager = null;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
}
}
}
}
Attempt to invoke virtual method 'double
android.location.Location.getLatitude()' on a null object reference
Your lastKnownLocation is null.
if(lastKnownLocation != null)
{
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
}
Related
I am working on an app that has a method called PostCar that when called should create a databasereference and add a child to My Firebase Consoles Lender table a child that contains the user's id and location. The problem is the location keeps getting marked as null. The code in my PostCar method that reads "geoFire.setLocation(userId,new GeoLocation(mlastlocation.getLatitude(),mlastlocation.getLongitude()));" keeps throwing the error "attempt to invoke virtual method 'double android.location.location.getlatitude()' on a null object reference". The devices location is on and I check for location permissions. Here is the code below.
package com.example.movir;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class LendersMenuPageActivity extends AppCompatActivity {
private String userId;
private FirebaseAuth mAuth;
private LocationManager lm;
Location mlastlocation;
LocationRequest locationRequest;
LocationCallback locationCallback;
private Button lendcarButton;
final LendCarForm cardlend = new LendCarForm(userId,"brand new Toyota","Toyota","Camry S9");
private FusedLocationProviderClient fusedLocationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lenders_menu_page);
mAuth = FirebaseAuth.getInstance();
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});
FirebaseUser currentUser = mAuth.getCurrentUser();
userId = currentUser.getUid();
DatabaseReference lendersReference = FirebaseDatabase.getInstance().getReference("Users").child("Lenders").child(userId);
lendcarButton = findViewById(R.id.lenders_car_button);
lendcarButton.setOnClickListener(onClick);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
if(getApplicationContext()!=null) {
mlastlocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}
}
}
};
mlastlocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
#Override
protected void onStart() {
super.onStart();
checkLocationPermission();
}
private void startLocationUpdates() {
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
}
public View.OnClickListener onClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(LendersMenuPageActivity.this,"hello",Toast.LENGTH_LONG);
postCar();
}
};
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("give permission")
.setMessage("give permission messaage")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(LendersMenuPageActivity.this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(LendersMenuPageActivity.this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
}
}
}
public void postCar(){
DatabaseReference carsForRent = FirebaseDatabase.getInstance().getReference("Users").child("Lenders").child(userId);
GeoFire geoFire = new GeoFire(carsForRent);
geoFire.setLocation(userId,new GeoLocation(mlastlocation.getLatitude(),mlastlocation.getLongitude()));
carsForRent.setValue(cardlend);
}
}
Are you testing this with the Xcode IOS simulator? The simulator can't actually access your real location so when queried it will return null unless specified manually (Features tab, Location, Custom Location.)
The reason fusedapi was not working for me is because i was not using a google maps project. So I overode onlocatiochanged instead. This worked for me, but you have to extend onlcationchanged and googleapi
I want to find out where my location is currently on the device connected to my computer, but since my location has not changed, it does not fall into the onLocationChanged function and therefore returns location = null. How do I enter the onLocationChanged function?
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLongClickListener(this);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
Like Sai suggested, you can use the fused location provider to retrieve the device's last known location which will display your current location.
Check out the working code sample below:
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private FusedLocationProviderClient fusedLocationClient;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) {
mapFragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (checkPermissions()) {
mMap.setMyLocationEnabled(true);
}
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
System.out.println("current location: " + location.toString());
} else {
System.out.println("current location is null");
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
System.out.println("error trying to get current location");
e.printStackTrace();
}
});
}
private boolean checkPermissions() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
requestPermissions();
return false;
}
}
private void requestPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1);
}
}
Hope it helps!
How do I log the GPS accuracy in meters with getAccuracy() in Android?
The following is my code. When I run it, I get a build error. I added in the getAccuracy() method, but strangely it returns an error.
package com.example.yires.locationdemo;
import android.Manifest;
import android.accounts.AccountAuthenticatorResponse;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("Location",location.toString());
Log.i("GetAccuracy",location.getAccuracy());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
I am a beginner in Android, so would appreciate any code help or explanation. Thank you once again.
To log float value, use String.valueOf(location.getAccuracy());
Log.i("HasAccuracy", String.valueOf(location.getAccuracy());
Trying to integrate GPS automatic tracker update but gets:
2018-10-03 19:06:45.256 1790-1861/? I/GnssLocationProvider: WakeLock acquired by sendMessage(REPORT_SV_STATUS, 0, com.android.server.location.GnssLocationProvider$SvStatusInfo#587390b)
2018-10-03 19:06:45.256 1790-1803/? I/GnssLocationProvider: WakeLock released by handleMessage(REPORT_SV_STATUS, 0, com.android.server.location.GnssLocationProvider$SvStatusInfo#587390b)
I get this when I try to Send new location to phone from emulator, virtual phone (Nexus). Have tried different Coords, and also restarting both Android studio, phone, and computer.
What I expect is the Log.d (tried them all), but that doesn't get output even if I run it in debug mode.
My code:
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("Location: ", location.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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.
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}else{
}
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng currentPositionVar = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(currentPositionVar).title("You are here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentPositionVar));
}
}
im writing android navigation app using geolocation but i have problem with frequency updating location.
picture
i get response in log.d() after approx 20 seconds. Im afraid its too slow for example when i use it while driving. The assumption is that the Marker should move smoothly.
NavigationActivity class:
package com.nowinski.kamil.drivertool;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import utils.LatLngInterpolator;
import utils.MarkerAnimation;
public class NavigationActivity extends FragmentActivity implements
OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private LocationManager locationManager;
private Location location;
private double latitude;
private double longitude;
private PlaceAutocompleteFragment placeAutocompleteFragment;
private Marker marker;
private Marker markerCurrentLocation = null;
private final float ZOOM = 12.2f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//initialize placeAutocompleteFragment and set on listener
placeAutocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
final LatLng latLngLoc = place.getLatLng();
if(marker!=null){
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(latLngLoc).title(place.getName().toString()));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}
#Override
public void onError(Status status) {
Toast.makeText(NavigationActivity.this, ""+status.toString(), Toast.LENGTH_SHORT).show();
}
});
//check permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
//initialize locationManager to get the location system service
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
private void updateMarkerPosition(Location newLocation){
//test
Log.d("locationChanged", Double.toString(newLocation.getLatitude())+" "+Double.toString(newLocation.getLongitude()));
LatLng newLatLng = new LatLng(newLocation.getLatitude(), newLocation.getLongitude());
//if marker used first time addMarker to map and move camera
if(markerCurrentLocation == null){
markerCurrentLocation = mMap.addMarker(new MarkerOptions().position(newLatLng));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newLatLng, ZOOM));
} else {
MarkerAnimation.animateMarkerToICS(markerCurrentLocation, newLatLng, new LatLngInterpolator.Spherical());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(newLatLng, ZOOM));
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
this.location = location;
updateMarkerPosition(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
//activity life cycle
#Override
protected void onDestroy(){
super.onDestroy();
//stop GPS
locationManager.removeUpdates(this);
}
}
There are detected activities when user is walking or driving or running. Google doc.
But i suggest you implement this by using these well tested and maintained libraries like
1.https://github.com/akexorcist/Android-GoogleDirectionLibrary
2.https://github.com/jd-alexander/Google-Directions-Android
Which provide you many in library functions to use. and you will need not to RnD on everything of location listening.