Fused Location Api Get time from GPS - android

I have an application that tracks users location.
My application uses FusedLocationApi , Google new way of getting device location using Google Play Services.
Provider of locations that i give from GPS is labeled as fused.
Because of application users may change device time, it is important to get real time from GPS.
Problem is that when i try to get time from Location object , it returns device time not GPS time.
Any solutions to get GPS time in this situation are appreciated.
private Location mLastLocation;
public void onConnected(Bundle arg0) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
public void onLocationChanged(Location location) {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Date date = new Date(mLastLocation.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String time = dateFormat.format(date)
}

To get GPS UTC, do it in normal way:
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
// not LocationManager.NETWORK_PROVIDER
#Override
public void onLocationChanged(Location location)
{
long utc = location.getTime();
// ....
}

Related

Getting approximate user location

locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
t= (TextView)findViewById(R.id.textView);
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
double lat = lastKnownLocation.getLatitude();
double lon = lastKnownLocation.getLongitude();
t.setText(""+lat+""+lon);
}
});
This is my code and I'm trying to get approximate location of user. But i don't know why i'm getting null object reference exception. Is this the right way of doing? can anyone help me with getting user location with network? Should I add request location updates method to get last known location?

Android Location Manager returning NULL

I have a simple location manager that normally works, however when the Android device has been turned off and then turned back on, the android location manager returns Null even when I have it requesting updates. I am aware that getLastKnownLocation can return null, however I believe I am handling that in my code. All suggestions Appreciated.
Apparently lon = location.getLongitude(); is crashing it.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
// request location update!!
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lon = location.getLongitude();
lat = location.getLatitude();
}
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Get last known location
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Update if not null
if (location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
//Request update as location manager can return null otherwise
else
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lat = location.getLatitude();
lon = location.getLongitude();
}
}
the android location manager returns Null even when I have it requesting updates
Correct. Requesting updates requests that Android start trying to find out where the device is. That will take a while. In the meantime, getLastKnownLocation() can very well return null.
getLastKnownLocation() is generally only useful if you would like to know the location, but if that data is not ready, you can move on without it. If you need the location, and getLastKnownLocation() returns null, you will to wait to use the Location until onLocationChanged() is called. Note that onLocationChanged() may never be called, as there is no requirement that the user have any location providers enabled, and there is no requirement that the device be in a position to actually get location fixes.
I saw your reply on the airplane mode but you do however have bad practices in your code.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
// request location update!!
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lon = location.getLongitude();
lat = location.getLatitude();
}
you already saw here that location in null, that means that you can't access the inner properties such as latitude and longitude. In any case, location requests are asynchronous and it takes a short amount of time for them to start.
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Get last known location
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Update if not null
if (location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
//Request update as location manager can return null otherwise
else
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lat = location.getLatitude();
lon = location.getLongitude();
}
}
Even here, in the "else" clouse, you can't access the location right away. that means that you can't immediately get the location (it will just hold the last value).
What you should do is implement the onLocationChanges method and hadle the location there in asynchronous way. like this:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
else
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lon = location.getLongitude();
}
The only problem was that I had airplane mode enabled on the Android Phone. I'm a bit embarrassed now!

Google glass- GDK app getSpeed() returns 0.0

I am trying to display the speed of the user on google glass live card.
I am able to get latitude and longitude,But getSpeed() always returns 0.0. I have checked similar questions on SO ,but of no help.
Here is my Code
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = mLocationManager.getBestProvider(criteria, true);
boolean isEnabled = mLocationManager.isProviderEnabled(provider);
if (isEnabled) {
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null) {
Geocoder geocoder = new Geocoder(Start_service.this.getBaseContext(), Locale.getDefault());
// lat,lng, your current location
List<Address> addresses = null;
try {
lati= location.getLatitude();
longi=location.getLongitude();
speed=location.getSpeed();
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e) {
System.out.println(e);
e.printStackTrace();
}
Location providers don't guarantee to provide the speed value. You can only getSpeed from the provider that calls setSpeed. You can set the Criteria variable to indicate that you need the speed value.
Criteria criteria = new Criteria();
criteria.setSpeedRequired(true);
Or you might consider to calculate it yourself. See why getSpeed() always return 0 on android.
Also, use hasSpeed() to check if a speed is available.

Get User Current City in Android

I want to fetch user's current city name in my Android application but as per some of my research (this, this, and this) it is a pretty complicated task and require switching between network providers and fetch location updates after some time.
My application is not some location-based app to require an accurate and up-to-date location of a user using the app. I just need a city name from NETWORK_PROVIDER (or any other provider for that matter) but if it is unable to fetch the city name, that's fine, too. It's just one feature in the application and doesn't matter if it fails to fetch the city name in some cases.
I'm using following code but it always shows both latitude and longitude to be 0.0.
Location location = new Location(LocationManager.NETWORK_PROVIDER);
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
Log.d("Lat-Lng", location.getLatitude()+","+location.getLongitude());
// Doesn't really return anything as both latitude and longitude is 0.0.
List<Address> address = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch(Exception e) {
}
Well all you are doing here is creating a new Location object whose initial values for latitude and longitude are zero by default.
What you need to do is connect that location to the GPS information of the user.
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location != null) {
Log.d("Lat-Lng", location.getLatitude()+","+location.getLongitude());
getUserGeoInfo(location.getLatitude(), location.getLongitude());
}
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.d("Lat-Lng", location.getLatitude()+","+location.getLongitude());
getUserGeoInfo(location.getLatitude(), location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Set how often you want to request location updates and where you want to receive them
locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
// ...
void getUserGeoInfo(double lat, double lon) {
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
if (Geocoder.isPresent()) {
List<Address> addresses = geoCoder.getFromLocation(lat, lon, 1);
if (addresses.size() > 0) {
// obtain all information from addresses.get(0)
}
}
}
The LocationListener interface can, for example, also be implemented by the Activity that holds this code and then you would only pass that activity's context as the third parameter in locationManager.requestLocationUpdates(provider, 20000, 0, context);. Of course, as with any interface implementation, you will have to override all the methods same way as in above code.
As far as the requestLocationUpdates() method, you can read more about it here
As far as general techniques for obtaining user location on Android, this is a definite read

issues to get the Latitude using network and GPS provider

Hi I have implemented a location listener in my app which uses the Network Provider to get the GPS values. It's working fine, but now I want to get GPS using network provider and GPS provider. am trying but am getting the same value.
here my code
Location networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Where i have to use networkLoc and gpsLoc?
#Override
public void onLocationChanged(Location location) {
double lat1 = (double) (location.getLatitude());//here i get the latitude value..how to know these values are from different provider
double lng1= (double) (location.getLongitude());
latituteField.setText(Double.toString(lat));
longitudeField.setText(Double.toString(lng));
}
It may be the case, that if the user has GPS Enabled your line
provider = locationManager.getBestProvider(criteria, false);
is returning LocationManager.GPS_PROVIDER already, so you just query getLastKnownLocation(provider) twice with the same Provider. Try this instead:
Location networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
or if you really don't care which one to use
List<String> providers = locationManager.getProviders(false);
Location[] loc = new Location[providers.size];
int i = 0;
for (String provider: providers){
loc[i++] = locationManager.getLastKnownLocation(provider);
}
EDIT: due to refactoring of the question
//query provider from Location
public void onLocationChanged(Location loc){
String provider = loc.getProvider();
if (provider.equals(LocationManager.GPS_PROVIDER)){
//GPS Location
} else if (provider.equals(LocationManager.NETWORK_PROVIDER)){
//Network Location
}
....
}

Categories

Resources