Simplest way to get rough user location in Android [duplicate] - android

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 .

Related

android :how to localise only with wifi or mobile network by code without using popup security menu

j know that since 4.0 it s impossible to trigger programmatically gps
but besides that there are three possibilities to localise
1) gps and wifi and mobile network (all together)
2) only wifi and mobile network
3) only gps
is there some possible code to get through the second one
so let's be clear j don't want to trigger wifi. that i know
j want to trigger localisation by whatever wifi (and)or mobile network without using gps
j tried to implement some object like skyhook' WPSPeriodicLocationCallback or WPSLocationCallback but
it doesn 't work without triggering the official android security menu
so what j want is getting through the positionning system only with wifi or internet connection and that by code
avast antitheft does that giving back some information with more or less accuracy .
i would like to reproduce the same
thanks in advance
You can get locating 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 or you can use this tutorial to get lat and lang.
Copypasted from this answer.

Android using LocationManager Get Provider is "Passive" in My Moto G Android Phone

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

android requestLocationUpdates failing

I am developing a proximity alert related project. For that whenever I opened my app, I need to get exact readings of where I am. Even though I am following the right coding practices prescribed by android documentation, I am not getting the expected result.
Why there is no alternative command in entire android Geolocation coding for getLastKnownLocation which will give us where we are earlier not now.
I have did one javascript coding in the same lines. There My code is working properly. The Descriptive address and coordinates where my device is working nice there. Those commands getCurrentPosition and watchPosition are givinga beautiful response via their event handler callbacks. Why there is no getCurrentLocation in android geolocation parlance?
Even though I have followed relevant coding practices, MyLocationListener myLocationUpdate which implements LocationListener is not updating my new location when I am moving from one place to another place. I gave MINIMUM_DISTANCE_CHANGE_FOR_UPDATES as 1(in meters) and MINIMUM_TIME_BETWEEN_UPDATES as 1000 (in milliseconds).
I am giving important code snippets below to understand the problem
in onCreate handler of the activity
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
myLocationUpdate = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, myLocationUpdate);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Finding Location",Toast.LENGTH_LONG).show();
showCurrentLocation();
}
});
latituteField = (TextView) findViewById(R.id.display_Location);
showCurrentLocation();
in showCurrentLocation function
I am using locationManager.getLastKnownLocation(provider) to retrieving that location.
By using GeoCoder Object and the command geocoder.getFromLocation(latitude, longitude, 1) to get First Address match for the coordinates.
// internal class to handle location cahnge event
private class MyLocationListener implements LocationListener contains all the Overridden functions including public void onLocationChanged(Location location)
But Practically I am getting nothing out of all the application. I have already recorded Time via location.getTime(). It is showing a fixed earlier time, but not the interval i specified.
the problem with getting GPS location is that it isnt available immediately. From my understanding of GPS location provider is that when you request location update, the gpr provider will try to connect to the gps satellites which runs in a separate thread (not entirely sure about it). In the meantime your program is executed normally and there maybe a chance that you wont get any location.
What you can do is use Fused Location Provide which was introduced in this year's IO Event. You can find the tutorial here

LocationManager and LocationClient together to get user location

I simply need to get the user location. Preferably the exactly location, but if it's not possible, a rough location would be fine.
According to the docs:
LocationClient.getLastLocation()
Returns the best most recent location currently available.
and
LocationManager.getLastKnownLocation(String)
Returns a Location indicating the data from the last known location fix obtained from the given provider.
If my understanding is right, the former will give me a very good result (or null sometimes) while the latter will give me a result which would rarely be null.
This is my code (simplified)
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationClient = new LocationClient(this, this, this);
#Override
public void onConnected(Bundle dataBundle) {
setUserLocation();
}
private void setUserLocation() {
myLocation = locationClient.getLastLocation();
if (myLocation == null) {
myLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
if (myLocation == null) {
//I give up, just set the map somewhere and warn the user.
myLocation = new Location("");
myLocation.setLatitude(-22.624152);
myLocation.setLongitude(-44.385624);
Toast.makeText(this, R.string.location_not_found, Toast.LENGTH_LONG).show();
}
} else {
isMyLocationOK = true;
}
}
It seems to be working but my questions are:
Is my understanding of getLastLocation and getLastKnownLocation correct?
Is this a good approach?
Can I get in trouble using both in the same activity?
Thanks
LocationClient.getLastLocation() only returns null if a location fix is impossible to determine. getLastLocation() is no worse than getLastKnownLocation(), and is usually much better. I don't think it's worth "falling back" to getLastKnownLocation() as you do.
You can't get into trouble using both, but it's overkill.
Of course, you have to remember that LocationClient is part of Google Play Services, so it's only available on devices whose platform includes Google Play Store. Some devices may be using a non-standard version of Android, and you won't have access to LocationClient.
The documentation for Google Play Services discusses this in more detail.

GPS doesn´t work in IntentService

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.

Categories

Resources