I am trying to get the current location of the user either by GPS or location provider but every solution I have tried (many from stacksoverflow and google, youtube as well) gives a null as latitude and longitude.
Here is the code I am using
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
double lat = 0;
double lng = 0;
provider = locationManager.getBestProvider(criteria, false);
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;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null)
{
lat = location.getLatitude();
lng = location.getLongitude();
Toast.makeText(this,"Location"+lat+" "+lng+" ",Toast.LENGTH_LONG).show();
}else
Toast.makeText(this,"Location"+lat+" "+lng+" ",Toast.LENGTH_LONG).show();
The above code always gives 0.0 and 0.0 as lat and long.
I have also included the permissions in Android Manifest :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Any suggestions please?
This is all I used for my project. Hope it helps!
Declarations:
Location location;
LocationManager locationManager;
String provider;
onCreate:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
locationManager.requestLocationUpdates(provider, 400, 1, this);
location = locationManager.getLastKnownLocation(provider);
lat = location.getLatitude(); long = location.getLongitude();
public static void getLocation(final Context context, final Looper looper, final LocationUpdateListener locationUpdateListener, final LocationListener locationListener) {
try {
boolean isProviderEnabled;
Location location;
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isProviderEnabled) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, looper);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.removeUpdates(locationListener);
}
getBackupLocation(context, looper, locationUpdateListener, locationListener);
}
}, 10000);
return;
}
}
isProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isProviderEnabled) {
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, locationListener, looper);
return;
}
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
if (locationUpdateListener != null) {
locationUpdateListener.onLocationUpdate(location);
locationManager.removeUpdates(locationListener);
}
return;
}
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
if (locationUpdateListener != null) {
locationUpdateListener.onLocationUpdate(location);
locationManager.removeUpdates(locationListener);
}
return;
}
float defaultValue = -10000;
SharedManager sharedManager = SharedManager.getInstance();
double lat = sharedManager.getDoubleValue(SharedManager.LAT, defaultValue);
double lng = sharedManager.getDoubleValue(SharedManager.LNG, defaultValue);
if (lat != defaultValue && lng != defaultValue) {
location = new Location(LocationManager.PASSIVE_PROVIDER);
location.setLatitude(lat);
location.setLongitude(lng);
if (locationUpdateListener != null) {
locationUpdateListener.onLocationUpdate(location);
locationManager.removeUpdates(locationListener);
}
return;
}
location = new Location(LocationManager.PASSIVE_PROVIDER);
location.setLatitude(PASSIVE_LAT);
location.setLongitude(PASSIVE_LONG);
if (locationUpdateListener != null) {
locationUpdateListener.onLocationUpdate(location);
locationManager.removeUpdates(locationListener);
}
}
catch(
Exception e)
{
//No Location
Location location = new Location(LocationManager.PASSIVE_PROVIDER);
location.setLatitude(PASSIVE_LAT);
location.setLongitude(PASSIVE_LONG);
if (locationUpdateListener != null) {
locationUpdateListener.onLocationUpdate(location);
}
}
}
Working function that checks GPS , Network and LastKnownLocation..
my Suggestion : First use LastKnownLocation then Netowrk and last Resort as GPS.. less Battery usage.
Location results return to the Listeners.
Related
Background: I am now working on an Android app to track vehicles where I required to get device location on every 10 second as on management decision. We are already developed this app which provides us updated location on time as our expected time interval.
Problem: When Vehicles are driving on the roads, the app gives us correct coordinates as our expected time interval, but sometime 5-20 minutes it provide same coordinates yet the vehicle is in a different location.
Code Review: 1) We use a method named getLocation() inside LocationClass that provide us latitude longitude of a device current location.
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5;
private static final long MIN_TIME_BW_UPDATES = 1000*20;
public Location getLocation(Context context) {
Location location=null;
try {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context,"Please! Provide Location Access Permission.....", Toast.LENGTH_LONG).show();
return TODO;
}
// if GPS Enabled get lat/long using GPS Services
if(isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
location.setProvider("GPS");
}
}
}
if (isNetworkEnabled && location==null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
location.setProvider("AGPS");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
2) We repeat this method using a timer on a service named GPSTracker at fixed time interval.
public class GPSTracker extends Service implements LocationListener {
private Timer mTimer = null;
private Handler mHandler = new Handler();
Location location;
#Override
public void onCreate() {
super.onCreate();
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 10 * 1000, 10 * 1000);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
location=new Location("");
LocationCls cls = new LocationCls();
location = cls.getLocation(getBaseContext());
}
});
}
}
}
I am trying to solve this issue a 2 long day but not found any coding problem or solution yet. Any Solution or Suggestion is highly appreciate.
Thanks in advance....
I try to get my current location with below code but it is return
longitude and latitude null or 0,0 in above mention device(Pixel os
8.0,Moto os 7.0,OnePlus 8.0).In other device with same os it is working fine.This is my code.
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
if (location == null || location.getAccuracy() < location.getAccuracy()) {
// Found best last known location: %s", l);
location = location;
}
}
}
}
Get Last Known Location Method
private Location getLastKnownLocation() {
locationManager = (LocationManager)mContext.getSystemService(LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
onLocationChanged(Location location) method
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
String add=addresses.get(0).getAddressLine(1)+", "+addresses.get(0).getAddressLine(2);
Try with the Fused Location API , which is a higher-level Google Play Services API that wraps the underlying location sensors like GPS.
Usage:
Add dependency in app/build.gradle
dependencies {
api 'com.google.android.gms:play-services-location:11.8.0'
}
Permissions required:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Connecting to the LocationServices API
private LocationRequest mLocationRequest;
private long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startLocationUpdates();
}
// Trigger new location updates at interval
protected void startLocationUpdates() {
// Create the location request to start receiving updates
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check whether location settings are satisfied
// https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(locationSettingsRequest);
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
// do work here
onLocationChanged(locationResult.getLastLocation());
}
},
Looper.myLooper());
}
and then register for location updates with onLocationChanged
public void onLocationChanged(Location location) {
// New location has now been determined
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
// You can now create a LatLng Object for use with maps
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}
For more info go through guides.codepath.com guide
public void getUserLocation() {
Location location;
TextView lon = (TextView) findViewById(R.id.textView2);
TextView lat = (TextView) findViewById(R.id.textView3);
boolean GpsEnable = false, NetworkEnabled = false;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// String locationProvider = LocationManager.GPS_PROVIDER;
GpsEnable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
NetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// locationManager.requestLocationUpdates(locationProvider,0,0,locationListner);
if (!GpsEnable && !NetworkEnabled) {
Toast.makeText(getBaseContext(), "No Provider Availabe",
Toast.LENGTH_SHORT);
} else {
if (NetworkEnabled)
Toast.makeText(getBaseContext(), "Network Provider Available",
Toast.LENGTH_SHORT);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
lon.setText("Latitude" + location.getLatitude());
lat.setText("Longitude " + location.getLongitude());
}
if (GpsEnable) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lon.setText("Latitude" + location.getLatitude());
lat.setText("Longitude " + location.getLongitude());
}
}
}
}
}
I had done both with GPS and network provider.. I want to know how we get exact current location in Google maps? Is there any way or algorithm by which i can get longitude and latitude of my location using internally Google maps?
Thanks in Advance
I have Followed this Tutorial for Fast Update and Initial SetUp for GoogleMap v2
Initial Setup Here
Alternative for LocationUpdate
Hope this could help...:)
public void retriveLocation(){
try {
String locCtx = Context.LOCATION_SERVICE;
LocationManager locationmanager = (LocationManager) context.getSystemService(locCtx);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationmanager.getBestProvider(criteria, true);
locationmanager.requestLocationUpdates(provider, 0, 0, this);
} catch (Exception e) {
}
}
Hope this code can be useful for retrieving fast location updates.
Here is the code that I basically use to get a constant location signal using Google Play Services.
public class MyActivity
extends
Activity
implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener
{
private LocationClient locClient;
private LocationRequest locRequest;
// Flag that indicates if a request is underway.
private boolean servicesAvailable = false;
#Override
protected void onCreate( Bundle savedInstanceState )
{
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
servicesAvailable = true;
} else {
servicesAvailable = false;
}
if(locClient == null) {
locClient = new LocationClient(this, this, this);
}
if(!locClient.isConnected() || !locClient.isConnecting())
{
locClient.connect();
}
// Create the LocationRequest object
locRequest = LocationRequest.create();
// Use high accuracy
locRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locRequest.setInterval(INTERVAL);
locRequest.setFastestInterval(INTERVAL);
}
#Override
public void onLocationChanged( Location location )
{
// DO SOMETHING WITH THE LOCATION
}
#Override
public void onConnectionFailed( ConnectionResult arg0 )
{
}
#Override
public void onConnected( Bundle arg0 )
{
// Request location updates using static settings
locClient.requestLocationUpdates(locRequest, this);
}
#Override
public void onDisconnected()
{
if(servicesAvailable && locClient != null) {
//
// It looks like after a time out of like 90 minutes the activity
// gets destroyed and in this case the locClient is disconnected and
// calling removeLocationUpdates() throws an exception in this case.
//
if (locClient.isConnected()) {
locClient.removeLocationUpdates(this);
}
locClient = null;
}
}
}
This is the crux of it anyway and I culled this from other sources so I can't really claim it but there it is.
This code:
ServiceListener mlistener = new SosServiceListener(getApplicationContext());
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlistener, null);
manager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, mlistener, null);
Attach a listener once to two events. The fact is: if both events are triggered, the listener is called twice? If yes, how would you prevent it?
Thanks!
This is what I used for one of my projects and is perfectly working:
public Location getLocation() {
try {
mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
// First get location from Network Provider
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (mLocationManager != null) {
location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
}
}
//get the location by gps
if (isGPSEnabled) {
if (location == null) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (mLocationManager != null) {location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
If you can assume that devices will be running on device with Google Play installed - much better way is to use this service: https://developer.android.com/training/location/retrieve-current.html
Recently, I created a simple application to get the GPS location and display it on an Android phone.
In the beginning I was able to get the location after a few tries. But, after I reinstalled the APK file, the getLastKnownLocation() always returns a null value.
The development environment:
API 10 Gingerbread 2.3.6
GPS provider is used
Below is the code I applied to my Android project:
public class MyActivity extends MapActivity {
protected void onCreate(Bundle savedInstanceState) {
mapView = (MapView) findViewById(R.id.myTripMap);
mapController = mapView.getController();
mapView.setSatellite(false);
mapView.setStreetView(true);
mapView.displayZoomControls(false);
mapView.setBuiltInZoomControls(true);//
mapView.setClickable(true);
mapController.setZoom(14);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
updateMyCurrentLoc(location);
locationManager.requestLocationUpdates(provider, 2, 1, locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateMyCurrentLoc(location);
}
public void onProviderDisabled(String provider) {
updateMyCurrentLoc(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
private void updateMyCurrentLoc(Location location) {
if (location != null) {
// other codes to get the address and display
Toast.makeText(getBaseContext(), "provider used : " + provider).show(); //testing purpose
} else {
str = "No location found";
Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show();
}
}
}
Can anyone suggest a possible solution to solve the null value returned by getLastKnownLocation()?
Try Following Code
LocationManager locationManager = (LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
Location lastlocation = locationManager.getLastKnownLocation(locationProvider);
String CurLat = String.valueOf(lastlocation.getLatitude());
String Curlongi= String.valueOf(lastlocation.getLongitude());
This solution is my little improvement for code by Ravi Tamada.
public Location getLocation() {
int MIN_TIME_BW_UPDATES = 10000;
int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10000;
try {
locationManager = (LocationManager) getApplicationContext()
.getSystemService(LOCATION_SERVICE);
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isPassiveEnabled = locationManager
.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled || isNetworkEnabled || isPassiveEnabled) {
this.canGetLocation = true;
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled && location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
if (isPassiveEnabled && location == null) {
locationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
}
if (isNetworkEnabled && location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
You just need to add one more line into the code
if (locationManager != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
Toast.makeText(
mContext,
"Location Null", Toast.LENGTH_SHORT).show();
}
}
I got the same issue after re-install via eclipse.
I solved going to Android settings / Security / app permissions and confirm location permissions to the application.