Get Location without using GPS and without Google Services via official API - android

I wonder if it's possible to get a location without Google Services and without using GPS (and thus using NETWORK_PROVIDER) on an Android device. My current code looks like this:
public void onButtonTap(View view) {
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// we're done here
printLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) { }
public void onProviderEnabled(String provider) { }
public void onProviderDisabled(String provider) { }
};
String provider = LocationManager.NETWORK_PROVIDER;
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
Location location = null;
try {
location = locationManager.getLastKnownLocation(provider);
} catch (SecurityException se) {
}
if(location != null) {
// we're done here
printLocation(location);
}
if(location == null) {
try {
locationManager.requestSingleUpdate(provider, locationListener, null);
} catch (SecurityException se) {
}
} // end of onButtonTab (formatting issues)
private void printLocation(Location location) {
String latitude = String.format(Locale.US, "%.4f", location.getLatitude());
String longitude = String.format(Locale.US, "%.4f", location.getLongitude());
String slocation = "lat: " + latitude + ", lon: " + longitude;
Toast.makeText(getApplicationContext(), slocation, Toast.LENGTH_LONG).show();
}
So I basically query for the last location and if there's none I request an update. This works for PASSIVE_PROVIDER (if there's GPS activity) and of course for GPS_PROVIDER but I don't get a location with NETWORK_PROVIDER. The listeners method onLocationChanged never gets called. The app has the right permissions and locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) is true.
Is this functionality just not working because there's no database (owned by Google and provided by Google Services) to compare against? Or does AOSP build it's own database over time (learning from GPS Data)? I doubt the later.
Little extra question: I can't use Fused Location Provider API as I don't have Google Services installed, can I?

Related

How do i get my current location without GPS?

I want to get my current latitude and longitude using Mobile network provider, not GPS. AKA it should work without GPS with just your sim card. i have found many tutorials online claiming they find location with gps or network. however, they all seem to use GPS only! here or here and also here i don't want last knows location, as i don't wish to use GPS
Try This Code you can get current location without opening GPS
btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
Do it via 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);

Gps not working sometimes in some of the applications for android

I was working with Gps for fetching current lat and long in my application, it was working nicely with android 2.3.3 and even in some of my higher versions android devices but sometimes in some of the devices its just behaving opposite although gps is on its showing error message that GPS is not connected please turn on the gps this is the message i used when gps is not detecting. can anyone please help me on this ?
Below is my code for detecting and getting GPS
private void bindgeocodelocation() {
latlong = new ArrayList<String>();
latlong = GeneralFunction.getcurrentlocation(Search.this);
if (latlong == null) {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location loc = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 1,
locationListener);
if (loc != null) {
latlong = new ArrayList<String>();
latlong.add("" + loc.getLatitude());
latlong.add("" + loc.getLongitude());
} else if (lm != null) {
lm.removeUpdates(locationListener);
}
}
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
try {
latlong = new ArrayList<String>();
latlong.add(location.getLatitude() + "");
latlong.add(location.getLongitude() + "");
// webviewdata();
} catch (Exception e) {
Log.e("Error", e.getMessage().toString());
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("Info", "Provider disable");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
Then if you make that device outdoor for some time, it may work. In some low end devices, gps may not work properly at all. Else try upgrading GooglePlayServices too. Also I suggest you to use multiple providers instead of only one NETWORK_PROVIDER
Sometimes the particular device's google play services are outdated
I've faced the similar problem.
Your code seems fine
The only issue can be the google playe services are outdated.

Android Location Services Not Updating requestLocationUpdates

I have a simple class GPSListener which gets the GPS coordinates:
public class GPSListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
} ...
Then trying to make use of this class in my activity, I simply invoke the class in my onCreate() function in my activity:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GPSListener();
Criteria criteria = new Criteria();
String bestProvider = mlocManager.getBestProvider(criteria, false);
mlocManager.requestLocationUpdates(bestProvider, 0, 0, mlocListener);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
lat = GPSListener.latitude;
lon = GPSListener.longitude;
Log.d("GPS", "lat: "+lat+" long:"+lon);
} else {
// TODO: GPS not enabled
Log.d("GPSERROR", "GPS not enabled");
}
But whenever I run the application, lat and lon in my activity are always zero. I'm not quite sure how to get around this issue.
When logging:
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
It returns the correct latitude and longitude, it just takes a second or two after the activity starts.
Log.d("GPSSUCCESS", "lat: "+lat+" long:"+lon);
Just returns 0.0 for both. I was under the impression that .requestLocationUpdates would pass the value to lat and lon before the if statement is executed. How can I accomplish this?
You are using public static field for latitude, longitude.
Please change it to non static and using setter, getter with instant object:
lat = mlocListener.getLatitude();
lon = mlocListener.getLongitude();
Google updated its location handling logic. It is now easier to listen location updates with fused location provider. You can implement your location listener in 5 min. Take a look.
Methods for getting the most accurate location
You are listening only gps provider and it is not ready(on waiting for location status) yet and then it does not return any location. Just take a look at fused location provider and write your location listener again.
try this...
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
return false;
}
});
user this Handler to get Location
private Handler customHandler = new Handler();
private Runnable updateTimerThread = new Runnable() {
#Override
public void run()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
secndLocationListener.onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
}
};
to run this
customHandler.postDelayed(updateTimerThread , 1000);
LocationManager uses the last known location from the cache. The cache is updated when you load google maps. Try this out, go out in the open and check your location. Move to a different location about 200m and check your location again. It will be same as the old one. Now, load google maps, you will notice that you application magically now has the new location.
You need to programmatically kick that cache to the latest location. The only way to do that is
YOUR_APPLICATION_CONTEXT.getLocationManager().requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});

device location is always null

I have gone through many posts on SO regarding this issue:
Tried everything in Here,
Here and Here Nothing works. Everytime location is null. On device and on emulator :(. My GPS is on,internet is on and my manifest has following permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
I use following code to get the location i.e the longitude and latitude of the device...however in every case I get location as null
public void find_Location() {
Log.d("Find Location", "in find_location");
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getApplicationContext()
.getSystemService(location_context);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
locationManager.requestLocationUpdates(provider, 1000, 0,
new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider,
int status, Bundle extras) {
}
});
Location location = locationManager.getLastKnownLocation(provider);
if (location == null) {
Toast.makeText(LbsGeocodingActivity.this, "Location Not found",
Toast.LENGTH_LONG).show();
} else {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(LbsGeocodingActivity.this,
"LAT..." + latitude + "\nLONG..." + longitude,
Toast.LENGTH_LONG).show();
// addr=ConvertPointToLocation(latitude,longitude);
// String temp_c=SendToUrl(addr);
}
}
}
It takes some time before the position is determined, and it can change over time. It's probably just not available yet when you check it.
When a position fix becomes available, you will be notified in onLocationChanged.
How could I be so stupid..My bad....In settings Use Wireless networks was not selected!....That cause all the problems !!
Now I am able to get a location.
It took me 16 hrs to get to this...my productivity going down for sure! :(

LocationManager will not return destination

I created this earlier on today, but it is not working. Location manager returns null, and I've even implemented the listener. Any ideas to the problems. thanks.
Edited:
I think this line is the problem
Location location = locationManager.getLastKnownLocation(provider);
Basically, if location is null, it will go into the else part of the if statement below it. Every time I compile the code, it will go into the else statement meaning it location is not updating.
public class Activity1 extends Activity implements LocationListener {
/** Called when the activity is first created. */
JoshTwoActivity main;
Activity2 two;
boolean checkTick = false;
String locationplace = "";
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println(provider);
System.out.println(locationManager.getProviders(criteria, false));
System.out.println(locationManager.getProvider("network"));
System.out.println(locationManager.getAllProviders());
Location location = locationManager.getLastKnownLocation(provider);
System.out.println(locationManager.isProviderEnabled(provider));
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
} else {
System.out.println("Provider not available");
System.out.println("Provider not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
getLastKnownLocation() returns a location with the last known location fix for a provider. If the provider returns null, the provider has never had a location fix. It doesn't mean the provider is not available.
Once you call getLastKnownLocation() you should check to see if the results are accurate or recent enough for your purpose. If not you should request location updates using requestLocationUpdates().
This blog post contains everything you need to know about writing code using location providers.
http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
Ok my first guess is that you are not giving location fix via command line or by using eclipse DDMS perpective. If this is problem go open DDMS perpecive and give latitude and longtiude you want and send it. So location will not be null from now on if this is the problem.
The following link may help you in understanding how to use emulator in finding the location. The last section of this page has that information.
http://developer.android.com/guide/topics/location/obtaining-user-location.html

Categories

Resources