This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I get the current GPS location programmatically in Android?
Got a code below.. Will this get me my own location..?
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude=loc.getLatitude();
longitude=loc.getLongitude();
}
public void onProviderDisabled(String provider)
{
//print "Currently GPS is Disabled";
}
public void onProviderEnabled(String provider)
{
//print "GPS got Enabled";
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
I know this has been asked several times.. Please help me with the code...
You may use this code to start listing for GPS updates and do something with the data you receive. It also prints messages in the log file for easy debugging. Please, note, this function does not return any results, it only starts listening to GPS. Results will be provided some time later in // do something here with the new location data part, when you may save them somewhere.
private void getGpsData() {
locationManager = (LocationManager) owner.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i(TAG, "location change:" + location.toString());
String longitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
if( location.hasAccuracy() ) { // good enough?
// do something here with the new location data
....
//
Log.i(TAG, "GPS listener done");
locationManager.removeUpdates(this); // don't forget this to save battery
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, provider + " status:" + status);
}
public void onProviderEnabled(String provider) {
Log.i(TAG, provider + " enabled");
}
public void onProviderDisabled(String provider) {
Log.i(TAG, provider + " disabled");
}
};
Log.i(TAG,"GPS listener started");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener );
}
Related
I will need to use Location data in multiple activities of my app and I was wondering if it was necessary to make a new LocationClient in each activity, or if there is a better way to create it once and access it from each activity. Any recommendations on how I should handle this?
I think it would be much better to create a single class for location listener and used it every where in your project.I have just created this in one of my package and in every class where i want to get the location values.I just call this.
LocationSender loc = new LocationSender(YourClass.this);
As i declared lat,lng as static so i can get any where its values.
double latitude = LocationSender.lat;
double longitude = LocationSender.lng;
LocationSender.java
public class LocationSender {
Context context;
LocationManager locationManager;
Location location;
static double lat,lng;
public LocationSender(Context ctx) {
context=ctx;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
// Acquire a reference to the system Location Manager
public void getNewLocation(Location location) throws JSONException
{
String latLongString = "";
if (location != null) {
this.location=location;
lat= location.getLatitude();
lng = location.getLongitude();
latLongString = "Lat:" + String.valueOf(LocationActivity.lat) + "\nLong:" + String.valueOf(LocationActivity.lng);
Log.d("Location Found", latLongString);
} else
{
location=null;
latLongString = "No location found";
}
Toast.makeText(context, latLongString, Toast.LENGTH_LONG).show();
}
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
try {
getNewLocation(location);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onProviderEnabled(String provider) {
Toast.makeText(context, "Provider: "+provider+" : Enabled", Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(context, "Provider: "+provider+" : disabled", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(context, "Provider: "+provider+" : status: "+status, Toast.LENGTH_LONG).show();
}
};
}
Also please dont forget to insert location permissions in AndroidManifest.xml :)
I am trying to get lat and lng and want to show that in a text box I want both mean Network address and GPS address so I have done this But every time I am getting only one address at a time
public class GetLocationMainActivity extends Activity {
double nlat;
double nlng;
double glat;
double glng;
LocationManager glocManager;
LocationListener glocListener;
LocationManager nlocManager;
LocationListener nlocListener;
TextView textViewNetLat;
TextView textViewNetLng;
TextView textViewGpsLat;
TextView textViewGpsLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_location_main);
//All textView
textViewNetLat = (TextView)findViewById(R.id.textViewNetLat);
textViewNetLng = (TextView)findViewById(R.id.textViewNetLng);
textViewGpsLat = (TextView)findViewById(R.id.textViewGpsLat);
textViewGpsLng = (TextView)findViewById(R.id.textViewGpsLng);
}
#Override
public void onDestroy() {
//Remove GPS location update
if(glocManager != null){
glocManager.removeUpdates(glocListener);
Log.d("ServiceForLatLng", "GPS Update Released");
}
//Remove Network location update
if(nlocManager != null){
nlocManager.removeUpdates(nlocListener);
Log.d("ServiceForLatLng", "Network Update Released");
}
super.onDestroy();
}
//This is for Lat lng which is determine by your wireless or mobile network
public class MyLocationListenerNetWork implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
nlat = loc.getLatitude();
nlng = loc.getLongitude();
//Setting the Network Lat, Lng into the textView
textViewNetLat.setText("Network Latitude: " + nlat);
textViewNetLng.setText("Network Longitude: " + nlng);
Log.d("LAT & LNG Network:", nlat + " " + nlng);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d("LOG", "Network is OFF!");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d("LOG", "Thanks for enabling Network !");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public class MyLocationListenerGPS implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
glat = loc.getLatitude();
glng = loc.getLongitude();
//Setting the GPS Lat, Lng into the textView
textViewGpsLat.setText("GPS Latitude: " + glat);
textViewGpsLng.setText("GPS Longitude: " + glng);
Log.d("LAT & LNG GPS:", glat + " " + glng);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d("LOG", "GPS is OFF!");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d("LOG", "Thanks for enabling GPS !");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public void showLoc(View v) {
//Location access ON or OFF checking
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
boolean networkWifiStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.NETWORK_PROVIDER);
//If GPS and Network location is not accessible show an alert and ask user to enable both
if(!gpsStatus || !networkWifiStatus)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(GetLocationMainActivity.this);
alertDialog.setTitle("Make your location accessible ...");
alertDialog.setMessage("Your Location is not accessible to us.To give attendance you have to enable it.");
alertDialog.setIcon(R.drawable.warning);
alertDialog.setNegativeButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
});
alertDialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Toast.makeText(getApplicationContext(), "Remember to give attandance you have to eanable it !", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
alertDialog.show();
}
//IF GPS and Network location is accessible
else
{
nlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
nlocListener = new MyLocationListenerNetWork();
nlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000 * 1, // 1 Sec
1, // 1 meter
nlocListener);
glocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
glocListener = new MyLocationListenerGPS();
glocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000 * 1, // 1 Sec
1, // 1 meter
glocListener);
}
}
}
Have you enable both NETWORK-LOCATION and GPS-LOCATION in Settings yet? As far as I know for Android ICS (4.x) and newer, due to the Security issue, you can't enable/disable location access programmatically. Try to test it on Android 2.x. Hope this helps.
You can use the new fused provider to get the user location quickly without confuse.
Location issues has been simplified with the new Google Play Services such as choosing best provider automatically depending on your priority.
Here is an example request;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(20000) // 20 seconds
.setFastestInterval(16) // 16ms = 60fps
.setNumUpdates(4)
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
Make sure you updated the Google Play Services in the SDK Manager and check out this link to get info about how to get users location with the new Play Services.
http://developer.android.com/training/location/retrieve-current.html
I am developing a small android application in which I want to find out the user's current location by using the network provider. I tried this in following ways but it's not giving me any output :
networklocationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("********************************",
"this is my network location " + location);
String Location_text = "NETWORK LOCATION latitude:"
+ location.getLatitude() + " longitude:"
+ location.getLatitude();
network_location.setText(Location_text);
}
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
networklocationManager
.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
networklocationListener);
I gave permissions in my manifest file like this
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
Is there any thing which I am missing ? Is this the correct way? Need help. Thank you...
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager gpslocationManager;
private LocationManager networklocationManager;
private LocationManager networklocationManager1;
private String provider;
private TextView gps_location;
private TextView network_location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gps_location = (TextView) findViewById(R.id.gps_location);
network_location = (TextView) findViewById(R.id.network_location);
networkLocation();
}
public void networkLocation() {
networklocationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("********************************",
"this is my network location " + location);
String Location_text = "NETWORK LOCATION latitude:"
+ location.getLatitude() + " longitude:"
+ location.getLatitude();
network_location.setText(Location_text);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
networklocationManager
.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
networklocationListener);
}
}
Make sure you enable Location Services in Settings! That should be the problem. It might be disabled (and this setting will usually be found in Location and Security in Settings)
Let me know if it works!
Is your network provider enabled?
boolean network_enabled;
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
ex.printStackTrace();
}
I hope this part of the code will help you extracted from vogella.
public class ShowLocationActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// 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, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location 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());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#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();
}
}
I am trying to get location using GPS provider or Network provider but i didn't get location from either GPS or Network.
Here is my code which was working fine some days ago but now it's not working.
I don't understand where i am wrong because all permission are already added in AndroidManifest.xml.
Here is the code which helpful for you to understand.
public class SearchDishoom extends Header implements LocationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchdish);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000000, 100, this);
locationListenerNetwork = 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) {}
};
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// if gps provider is not enable then popup alertbox
buildAlertMessageNoGps();
} else {
// if gps is one then start searching
locationListenerGps = 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) {}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000000,100, locationListenerGps);
}
}
/*
* Get location (lat-long) from sharedpreference to further use
*/
prefLocation = getSharedPreferences("myLocation", MODE_WORLD_READABLE);
String userLocationLat1 = prefLocation.getString("Lat", String.valueOf(0));
String userLocationlong1 = prefLocation.getString("Long", String.valueOf(0));
String address = prefLocation.getString("Address", "Location not found not found");
userLocationLat = Double.parseDouble(userLocationLat1);
userLocationlong = Double.parseDouble(userLocationlong1);
// set lat-long value in getset class for use of another activity
gs = new GetSet();
gs.setLatitude(userLocationLat);
gs.setLangitude(userLocationlong);
if (userLocationLat == 0 && userLocationlong == 0 && address.equals("")) {
/*
* if lat-long is 0 or null then start searching using
* GPS Provider or Network Provider
*/
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000000,100, locationListenerGps);
}
} else {
// set lat-long value in getset class for use of another activity
gs.setLatitude(userLocationLat);
gs.setLangitude(userLocationlong);
setLocationName(userLocationLat, userLocationlong);
}
}
Here is override onLocationchanged():
#Override
public void onLocationChanged(Location location) {
userLocationLat =location.getLatitude();
userLocationlong =location.getLongitude();
prefLocation = getSharedPreferences("myLocation", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = prefLocation.edit();
prefsEditor.putString("Lat", String.valueOf(userLocationLat));
prefsEditor.putString("Long", String.valueOf(userLocationlong));
gs.setLatitude(userLocationLat);
gs.setLangitude(userLocationlong);
List<Address> addresses;
try {
addresses = new Geocoder(SearchDishoom.this, Locale.getDefault())
.getFromLocation(userLocationLat, userLocationlong, 1);
Address obj = addresses.get(0);
add = obj.getAddressLine(0);
city = obj.getLocality();
addressString = add + "," + city;
gs.setCurrentAddressString(addressString);
prefsEditor.putString("Address", addressString);
prefsEditor.commit();
tvLocation.setText(add + "," + city);
} catch (IOException e) {
showToast("Unable to find location");
}
}
Even i am not getting location using Geocoder, If i enter city name then it show me "Unable to find location".
Here is trick, GeoCoder is working on Emulator but not working on phone(i tried 2 different handset).
My project is build in API 17 and no any logcat error.
Please give me any hint or reference.
Maybe you should check "location access" settings and allow access to your location?..
While I cant immediately tell whats wrong with your code, you should consider maybe using a location library and let others do the heavy lifting. See: https://code.google.com/p/little-fluffy-location-library/
I use below code to get current location of user. This code work in emulator but when I use this application in mobile it unable to give current latitude and longitude.
I uses <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> this code in android manifest file.
Please give me solution... my code is below
public class MenuPage extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menupage);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
/* Start of Class MyLocationListener for get current location of user */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location crurrentLocation)
{
Log.v("WHERE ","onLocationChanged()");
crurrentLocation.getLatitude(); // get current latitude
crurrentLocation.getLongitude(); // get current longitude
longitude=crurrentLocation.getLongitude();
latitude= crurrentLocation.getLatitude();
Log.v("WHERE ","onLocationChanged() Latitude="+latitude);
Log.v("WHERE ","onLocationChanged() Longitude="+longitude);
Toast.makeText(getApplicationContext(),"Latitud="+crurrentLocation.getLatitude(),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Longitud="+crurrentLocation.getLongitude(),Toast.LENGTH_SHORT).show();
send_current_location = new Send_Current_location_ToServer();
// Send current location to server
String server_message = send_current_location.sendData(userid,latitude,longitude);
// String text ="My current location is: " + "Latitud = " + crurrentLocation.getLatitude() + "Longitud = " + crurrentLocation.getLongitude();
// Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Log.v("WHERE ","onProviderDisabled()");
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Log.v("WHERE ","onProviderEnabled()");
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.v("WHERE ","onStatusChanged()");
}
}/* End of Class MyLocationListener */
}
There is a bug in the 2.3 emulator concerning the location services. Try changing to 2.1 to test your code.
For more info about location services, use this.
See here for the status of the bug.