I have tried following code but not getting current location.
When I manual set location at emulator control then I get such location but not getting current location .I get null location.
How to get current location?
Is there any other way to get current location?
This is my code:
package com.p;
import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class GooglemapActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
EditText t;
#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();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);//true if required
criteria.setBearingRequired(false);//true if required
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
//provider=LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
/*check provder*/boolean statusOfGPS =locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if ( statusOfGPS==true) {
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField.setText(Double.toString(lat));
longitudeField.setText(Double.toString(lng));
} else {
latituteField.setText("Provider is not available");
longitudeField.setText("Provider not available");
}
}
else
{
latituteField.setText("eeeeeeeee");
longitudeField.setText("rrrrrrrrr");
}
}
/* 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);
}
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField.setText(Double.toString(lat));
longitudeField.setText(Double.toString(lng));
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
I have added permissions in manifest.xml as below:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
You won't get current location in emulator. You can set them through DDMS, and they will be your current location in case of a emulator.
Please, don't try to get last-known-location, most of the time it's stale and useless. Set up locationListener instead and wait for the location updates. This will get you your current location.
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
My app doesnt want to use GPS and using network to get location instead. I checked that by analysing latitude and longtitude, they're a little bit random (like network location).
If I use another app using GPS (e.g Endomondo Sports tracker) I see characteristic mark, which means, that GPS is currently working:
When I launch my application, there's no mark at all.
I'm using following code (code by Lars Vogella, Source: http://www.vogella.com/articles/AndroidLocationAPI/article.html):
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class ShowLocationActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
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);
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) {
// 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();
}
}
Of course I added permissions in AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Any ideas?
Solution:
you can use GPS instead of selecting best provider by deciding criteria.
Example, Replace:
locationManager.requestLocationUpdates(provider, 400, 1, this);
With:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1, this);
Explaination:
Depending on your application's use case, you have to choose a specific location provider
i.e. LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER
Alternatively, you can provide some input criteria such as accuracy, power requirement, monetary cost, and so on, and let Android decide a closest match location provider
// Retrieve a list of location providers that have fine accuracy, no monetary cost, etc
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(false);
String providerName = locManager.getBestProvider(criteria, true);
//and then you can make location update request with selected best provider
locationManager.requestLocationUpdates(provider, 400, 1, this);
Have a look at how to use locationmanager , how to specify Criteria and how getBestProvider method works for reference
i am building a simple android application which require me to auto update the location. the auto update location will not only update when resuming the application but must auto update whenever the application is on. this application looks like the same with GPS system that were put inside the car. it get the exact location and always update the current location. i want to the same thing in here. i am building this application on android 2.2.
here is my code:
package com.example.map;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.widget.Toast;
public class MapActivity extends Activity implements LocationListener{
private TextView latituteField, longitudeField, accuracyField, altitudeField, bearingField;
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
accuracyField = (TextView) findViewById(R.id.textView1);
altitudeField = (TextView) findViewById(R.id.textView2);
bearingField = (TextView) findViewById(R.id.textView4);
// 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());
int acc = (int) (location.getAccuracy());
int alt = (int) (location.getAltitude());
int bearing = (int) (location.getBearing());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
accuracyField.setText(String.valueOf(acc));
altitudeField.setText(String.valueOf(alt));
bearingField.setText(String.valueOf(bearing));
}
#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();
}
this code it only update the location value when im resuming the application (i quit the application then go back to the application). the location will be updated at the viewtext.
i also tried to do while. like this.
if(location != null){
do{
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
locationManager.requestLocationUpdates(provider, 0, 0, this);
}while(location != null);
}
else{
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
im adding this to the manifest.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
however, this code makes the application crash in a real phone. is there anyway to get this done?
*note: i tested all this application in my real phone and trying to achieve the current location. the textview suppose to change whenever it gets the new value of the location without pausing or quitting the application.
You have to put your location code inside an ScheduledExecutor Service:
http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
That one repeats actualization function in the background for example every 30 seconds or whatever time you specify.
Example:
scheduleTaskExecutor= Executors.newScheduledThreadPool(5);
// This schedule a task to run every 10 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
//add your code you would like to be executed every 10 seconds.
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 10, TimeUnit.SECONDS);
you also might have to add a permission for coarse location.
I want to get latitude and Longitude from the following Android code.
location = locationManager.getLastKnownLocation(provider);
Here i am getting error location is null.
Here is the code:
package com.p;
import android.app.Activity;
import android.os.Bundle;
import android.os.Bundle;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class GooglemapActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
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);
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.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("Provider not available");
longitudeField.setText("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);
}
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));
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
I have added the following permisions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
But I am getting the following error:
Provider not available
If the last known location is null, it's because the phone has no last known location. If there is no location cached, you need to request an updated location, either via network, or GPS. Note that this process can take time, so must be done asynchronously.
You need to read this document:
http://developer.android.com/guide/topics/location/obtaining-user-location.html
I also recommend reading this:
http://android-developers.blogspot.co.uk/2011/06/deep-dive-into-location.html
You haven't define a valid Criteria. Define that as follows
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);//true if required
criteria.setBearingRequired(false);//true if required
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);//search for enabled provider
have you switched on GPS in Settings -> Location ?
why do you use (int) (location.getLatitude()) -- latitude/longitude is a float
Think you need to specify from which provider you want to receive updates.
You have two options:
GPS_PROVIDER
NETWORK_PROVIDER
You're probably missing something like this:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
I think you may want to add the following permission as well, since I am pretty sure that the FINE relies on the COARSE...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
I have implemented sample application for get the current location latitude longitude.If i lunch my application in emulator and i am sending latitude and longitude from Emulator Controls at eclipse then i am getting current location latitude and longitude which from emulator controls.If i lunch the same application in real device then i am not able to get current location latitude and longitude
I have implemented code for get the current location latitude and longitude as follows:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 11, 11, mlocListener);
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
Log.v("11111","Latitude :"+loc.getLatitude());
Log.v("22222","Longitude :"+ loc.getLongitude());
}
}
From the above code i am not getting current location latitude and longitude in real android device.
How can i get current location latitude and longitude of real device?
please any body help me
GPS_PROVIDER does not work in bound place. So if gps_provider is enabled but you get null location you can replace provider from gps to NETWORK_PROVIDER.
prasad try this code ..by using this i am successfully getting lat long
private Location location = null;
private LocationManager locationManager = null;
locationManager = (LocationManager) context.getSystemService (Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
locationCritera.setAccuracy(Criteria.ACCURACY_FINE);
locationCritera.setAltitudeRequired(false);
locationCritera.setBearingRequired(false);
locationCritera.setCostAllowed(true);
locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT);
String providerName = locationManager.getBestProvider(locationCritera,
true);
location = locationManager.getLastKnownLocation(providerName);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
currentLocation = context.getSharedPreferences(PREFS_NAME, 0);
editor = currentLocation.edit();
}
public String getCurrentLatitude() {
try {
if (!currentLocation.getString("currentLatitude", "")
.equalsIgnoreCase(""))
return currentLocation.getString("currentLatitude", "");
else if (location.getLatitude() != 0.0)
return Double.toString(location.getLatitude());
else
return "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return "0.0";
}
public String getCurrentLongitude() {
try {
if (!currentLocation.getString("currentLongitude", "")
.equalsIgnoreCase(""))
return currentLocation.getString("currentLongitude", "");
else if (location.getLongitude() != 0.0)
return Double.toString(location.getLongitude());
else
return "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return "0.0";
}
are you trying on emulator or device. if you are trying in device then your device should have to be near window or in open place.
override these methods in your MyLocationListener. so that you can track your GPS status. check and see if you can get whats the problem
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
On a real device, you will have to be patient and wait for a fix from the satellites. This can take several minutes, even with a clear view of the sky.
For testing outside, you would be better advised to have a simple text box in your app, initialise it to something like "No GPS fix yet", then send a string comprised of the lat/long coordinates to it when the location changes.
Maybe this is more clear. I will change the conditional to something more efficient later if it is possible
double longitude = 0;
double latitude = 0;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null) {
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else {
Location location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
}
There are two types of location providers,
GPS Location Provider
Network Location Provider
package com.shir60bhushan.gpsLocation;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
This Link can help you for more information
http://androidtutorials60.blogspot.in/2013/09/gps-current-location-of-device.html
I want to display latitude and longitude my current location..
For this rather than searching in Google, i searched in SO.
I just want to display my current location latitude and longitude.
See my code below :
public class LocationGetter extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
LocationManager mlocManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new LocationManagerHelper();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100,mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
+ '\n');
tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
+ '\n');
Log.i("MyLocation1",Double.toString(LocationManagerHelper.getLatitude())+" "+Double.toString(LocationManagerHelper.getLongitude()));
} else {
tv.setText("GPS is not turned on...");
}
/** set the content view to the TextView */
setContentView(tv);
}
/* Class My Location Listener */
public static class LocationManagerHelper implements LocationListener {
private static double latitude;
private static double longitude;
#Override
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
}
#Override
public void onProviderDisabled(String provider) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public static double getLatitude() {
return latitude;
}
public static double getLongitude() {
return longitude;
}
}
}
I have also added permission in manifest file :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
See the output i am getting :
Where i am going wrong ? I dont understand, its a simple code and why its not working ?
I just verified your code and it works with these changes, you just need to move the tv.append() calls to the onLocationChanged() method as that is called each time, if you don't use that for the CallBack, then u will get the first set values only and it's only executed once.
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
+ '\n');
tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
+ '\n');
Log.i("MyLocation1",Double.toString(LocationManagerHelper.getLatitude())+" "+Double.toString(LocationManagerHelper.getLongitude()));
}
and I have used these permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
You can look at these and filter out the ones you won't be interested in. I have used a downloaded .gpx file from here
I've tested it on Android 2.2 though,
You got location in Onlocationchanged
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
}
so the lattitude and longitude will be displayed only when the change from the current location.for checking you give some latitude and longitude and send from your emulator control in DDMS and after that you run your program.Sure it will show the location.
If you run this program in device then it show latitude and longitude 0.0 until we change our position.You must move at least 10 meter from your current position to see the output. Because without change current position onLocationChange() method does not fire and output will be 0.0
Use the LocationManager.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
I think with the emulator you can't get the GPS co-ordinates. If you are working with the mobile, try the GPS outside of your building. sometimes you won't get the GPS co-ordinates inside the building. If that time also you failed, then i will post the code that we got succeeded.
The below code just now i have tested and its works for me..
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class GetGPS extends Activity {
String GPSPROVIDER = LocationManager.GPS_PROVIDER;
private static final long MIN_GEOGRAPHIC_POOLING_TIME_PERIOD = 10000;
private static final float MIN_GEOGRAPHIC_POOLING_DISTANCE = (float)5.0;
public LocationManager gpsLocationManager;
static Context context = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
/*Get a listener for GPS*/
LocationListener gpsLocationListener = null;
gpsLocationListener = new GpsLocationListener(this);
/*Start Location Service for GPS*/
gpsLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
/*Register GPS listener with Location Manager*/
gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_GEOGRAPHIC_POOLING_TIME_PERIOD,
MIN_GEOGRAPHIC_POOLING_DISTANCE, gpsLocationListener);
boolean isavailable = gpsLocationManager.isProviderEnabled(GPSPROVIDER);
if(isavailable) {
Location loc = gpsLocationManager.getLastKnownLocation("gps");
if(loc != null) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(GetGPS.this,"Longitude is "+longitude + " Latitude is "+latitude, Toast.LENGTH_LONG).show();
}
}
}
public static class GpsLocationListener implements LocationListener {
public GpsLocationListener(Context context){
}
public void onLocationChanged(Location loc) {
if (loc != null) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(context,"Longitude is "+longitude + " Latitude is "+latitude, Toast.LENGTH_LONG).show();
}
}//End of onLocationChanged Method
#Override
public void onProviderDisabled(String provider) {
}//End of onProviderDisabled Method
#Override
public void onProviderEnabled(String provider) {
}//End of onProviderEnabled Method
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}//End of onStatusChanged Method
}//End of GpsLocationListener class
}
I tested this by moving the device from one place to another...
I hope it will helps..