Reputation:
How can we retrieve the location in android with out turning on GPS. I was able to get the location using the GPS,NETWORK Providers. When the GPS was disabled not able to get the coordinates. Could anyone help me out. Thanks in advance
Upvotes: 0
Views: 4200
Reputation: 789
Go through this tutorial. http://www.vogella.com/tutorials/AndroidLocationAPI/article.html
Here is the sample code you can use to retrieve location from default location provider.
public class ShowLocation extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
}
/* 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) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
}
@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, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Add the following permissions to your application in your AndroidManifest.xml file
I hope this helps.
Upvotes: 1
Reputation: 1302
Getting Location using network providers:
boolean network_enabled = isNetworkAvailable();
Location location = null;
LocationManager locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if(network_enabled)
location = SLOC_locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
The isNetworkAvailabel() function:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) SLOC_context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Upvotes: 0