hi guys i am trying to get current location with location manager, i am using this below code
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider =locationManager.getBestProvider(criteria,true);
Location location =
locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0,this);
But i am not getting any response for this line
locationManager.requestLocationUpdates(bestProvider, 20000, 0,this);
and also getting lastknown location as null, i have added all permissions in manifest as well as dynamic, but this above line is not giving any response, i searched for it but dint get and relevant answer , please help.
For the getLastKnownLocation method, it is said in the documentation :
If the provider is currently disabled, null is returned.
Which means your GPS is disabled.
For the requestLocationUpdates, you are requesting a location every 20 seconds, try to decrease this number so you know at least if your program is working.
You can try this :
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Also I really advise you to use the new API to request location updates : https://developer.android.com/training/location/receive-location-updates.html
It is very fast and accurate, but you need to create a google developer account (for free) and create an api key. All needed information should be in the link.
String bestProvider =locationManager.getBestProvider(criteria,true);
In the above line, the second boolean parameter is true. That means it will fetch the provider which is enabled. And you the GPS_PROVIDER is disabled which is validated by the fact that locationManager.getLastKnownLocation returns null.
Moreover, since your Criteria for requesting BestProvier is empty so you must be getting "passive" as your BestProvider. Which means you will receive location updates only when other applications request and receives updates.
To get real location updates in onLocationChangedMethod() of your class. You must ensure these things:
Make sure that you have either one of ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION and then request it in runtime too, which you say you have already done.
If you want to request location through GPS_PROVIDER then you need to make sure that GPS_PROVIDER is enabled you can do that using below code:
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // OR some other PRIORITY depending upon your requirement
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient,
builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can
// Request for location updates now
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
status.startResolutionForResult(YourActivity.this, 100); // First parameter is your activity instance
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way
// to fix the settings so we won't show the dialog.
Log.e("TAG", "Error: Can't enable location updates SETTINGS_CHANGE_UNAVAILABLE");
break;
}
}
});
LocationManager.NETWORK_PROVIDER need network, but it is real, not precise.
if you want to use LocationManager.GPS_PROVIDER, the situation must be outdoor instead of indoor, because GPS location need satellite, if you are in any building, the satellite cannot find you!
pleasle go outdoor and check with GPS_PROVIDER again!
*best approach is getting location from both of GPS and NETWORK and check any of then that was not null and more accurate useing it.
Related
Is it possible to get the current location of user without using GPS or the internet? I mean with the help of mobile network provider.
What you are looking to do is get the position using the LocationManager.NETWORK_PROVIDER instead of LocationManager.GPS_PROVIDER. The NETWORK_PROVIDER will resolve on the GSM or wifi, which ever available. Obviously with wifi off, GSM will be used. Keep in mind that using the cell network is accurate to basically 500m.
http://developer.android.com/guide/topics/location/obtaining-user-location.html has some really great information and sample code.
After you get done with most of the code in OnCreate(), add this:
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// 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.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You could also have your activity implement the LocationListener class and thus implement onLocationChanged() in your activity.
By getting the getLastKnownLocation you do not actually initiate a fix yourself.
Be aware that this could start the provider, but if the user has ever gotten a location before, I don't think it will. The docs aren't really too clear on this.
According to the docs getLastKnownLocation:
Returns a Location indicating the data from the last known location
fix obtained from the given provider. This can be done without
starting the provider.
Here is a quick snippet:
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;
public class UtilLocation {
public static Location getLastKnownLoaction(boolean enabledProvidersOnly, Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location utilLocation = null;
List<String> providers = manager.getProviders(enabledProvidersOnly);
for(String provider : providers){
utilLocation = manager.getLastKnownLocation(provider);
if(utilLocation != null) return utilLocation;
}
return null;
}
}
You also have to add new permission to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
No, you cannot currently get location without using GPS or internet.
Location techniques based on WiFi, Cellular, or Bluetooth work with the help of a large database that is constantly being updated. A device scans for transmitter IDs and then sends these in a query through the internet to a service such as Google, Apple, or Skyhook. That service responds with a location based on previous wireless surveys from known locations. Without internet access, you have to have a local copy of such a database and keep this up to date. For global usage, this is very impractical.
Theoretically, a mobile provider could provide local data service only but no access to the internet, and then answer location queries from mobile devices. Mobile providers don't do this; no one wants to pay for this kind of restricted data access. If you have data service through your mobile provider, then you have internet access.
In short, using LocationManager.NETWORK_PROVIDER or android.hardware.location.network to get location requires use of the internet.
Using the last known position requires you to have had GPS or internet access very recently. If you just had internet, presumably you can adjust your position or settings to get internet again. If your device has not had GPS or internet access, the last known position feature will not help you.
Without GPS or internet, you could:
Take pictures of the night sky and use the current time to estimate your location based on a star chart. This would probably require additional equipment to ensure that the angles for your pictures are correctly measured.
Use an accelerometer to track location starting from a known position. The accumulation of error in this kind of approach makes it impractical for most situations.
boolean gps_enabled = false;
boolean network_enabled = false;
LocationManager lm = (LocationManager) mCtx
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location net_loc = null, gps_loc = null, finalLoc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gps_loc != null && net_loc != null) {
//smaller the number more accurate result will
if (gps_loc.getAccuracy() > net_loc.getAccuracy())
finalLoc = net_loc;
else
finalLoc = gps_loc;
// I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)
} else {
if (gps_loc != null) {
finalLoc = gps_loc;
} else if (net_loc != null) {
finalLoc = net_loc;
}
}
Here possible to get the User current location Without the use of GPS and Network Provider.
1 . Convert cellLocation to real location (Latitude and Longitude), using "http://www.google.com/glm/mmap"
2.Click Here For Your Reference
Have you take a look Google Maps Geolocation Api? Google Map Geolocation
This is simple RestApi, you just need POST a request, the the service will return a location with accuracy in meters.
It appears that it is possible to track a smart phone without using GPS.
Sources:
Primary: "PinMe: Tracking a Smartphone User around the World"
Secondary: "How to Track a Cellphone Without GPS—or Consent"
I have not yet found a link to the team's final code. When I do I will post, if another has not done so.
You can use TelephonyManager to do that .
I need a little help with some information about LocationManager in Android. I'm using this code to get user's specific information depending on his location,but in My Device Motorola G I get provider="Passive" and also Location return Null My Motorola G is running on Latest Android Kit Kat(4.4) Android Os.
I also try this code in Other Devices so Provider is either Network Or GPS also find Location properly.
locationManager = (LocationManager) getSherlockActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 1000, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getSherlockActivity(), "Location not available", Toast.LENGTH_SHORT).show();
}
I know that this is somehow an old question. But hope my answer will help others as well.
The issue is not related to the used device, actually the issue is how we use the provided API.
In the following code snippet, you pass true for the enabledOnly flag while you just need to pass it as false and it will work correctly at this time.
Instead of :
provider = locationManager.getBestProvider(criteria, true);
To be:
provider = locationManager.getBestProvider(criteria, false);
To clear this point:
If we set this flag "enabledOnly flag" to true, this means to return the requested best provider based on our criteria from the enabled only providers which will return the Passive provider.
While, if we set it to false, this will mean to return the requested best provider based on our criteria even if it is not enabled, which will return gps.
Btw, I am using Moto G too -but it's 2nd Gen- , and it worked with me this way :)
Hope this helps :)
READ THIS IF YOUR APP SUPPORTS kITKAT(4.4) VERSION OF ANDROID
I was having the same issue and my code was working perfectly in other devices not running kitkat,after a little bit of snooping around i found out that you have to explicitly turn on GPS to get location through wifi/gps. you can read about it here.
https://support.google.com/nexus/answer/3467281
I am using Google Map V2 and i trying to get the current location.But it is always returning null .
Code
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Every time i am getting location null .My GPS is working fine in my device what can the issue please help me.
Per the getLastKnownLocation documentation:
If the provider is currently disabled, null is returned.
as you are using getBestProvider(criteria, false) you are saying you allow providers that are not enabled (that's what false means) - switch it to true if you only want to look at enabled providers (which will assure that getLastKnownLocation does not return null).
Note that the getLastKnownLocation could be very out of date and you may still want to look for location updates if you need to get a recent location.
There are different approach. First of all be sure that you have all required permission in your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
If you only want an approximate location you can get the lastlocation (GPS or NETWORK)
if(_locationManager != null)
{
if(_locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null)
return new Location(_locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER),true);
else if(_locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) != null)
return new Location(_locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER),true);
}
I have the following code in my Service:
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider =
locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();
Location location = locationManager.getLastKnownLocation(provider);
while(true)
{
if(...)//every 5 seconds it gets into
{
....//control if the location is not null
lat = location.getLatitude();
lon = location.getLongitude();
alt = location.getAltitude();
Log.i(TAG, "Latitude: "+lat+"\nLongitude: "+lon+"\nAltitude: "+alt);
}
else {
Log.i(TAG, "Error!");
}
}
This code kind of works in my emulator (GPS are inserted into the Log), but in my Mobile device, this code gets to the else branch. Could somebody tell me where is the problem? In my code or in my Mobile device? Thanks in advance.
P.S.: The GPS is turned on, in another apps it works.
getLastKnownLocation() will not fetch subsequent location from the GPS provider. It will return (as the name may suggest) the last known location requested by some code. I assume that you check location being not null in the condition, which is not shown in your code. The location is null if the device "decided" that the last known location is too old or unreliable by other means. You need to request location updates and provide a location listener to get locations repeatetly.
There are lots of tutorials available. Here ist one. of them.
Actually my problem is sometimes i can get the location and sometimes i can't get the location on Android real device. I used following code for getting the location,
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
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);
Location location = locationManager.getLastKnownLocation(provider);
I need to get the location when my application starts up. I don't know why sometimes it fails. How to resolve this issue?
#jsmith commented on my quesion,
Increase your power requirements and make sure you test where you can
get a network or gps signal. If that helps, then it's simply a case of
the sensors not getting enough reception to know the location.
This is the right answer for my question. Now its working fine.
You forgot to request for 'Location Updates', use this function after declaring the LocationManager:
locationManager.requestLocationUpdates(provider, 0, 0, this);
and you have to let the class implements LocationListener then add this function:
public void onLocationChanged(Location location) {
//get the location here
}
If you don't want to get the location repeatedly, after you get the location you have to stop the 'Location Updates' this way:
locationManager.removeUpdates(this);
in case you want the application always listen for the 'Location Updates', you better request for updates in onResume() and remove the updates in onPause() & onDestroy()
Good Luck