问题
I am developing android app to get my current longitude and latitude from GPS. I have the following code
public class setting extends Activity {
TextView longval;
TextView latval;
@Override
public void onCreate(Bundle savedInstanceState){
/** Called when the activity is first created. */
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
longval = (TextView)findViewById(R.id.longitudefield);
latval = (TextView)findViewById(R.id.latitudefield);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//Location lastLocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
LocationListener locationListener = new myLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
class myLocationListener implements LocationListener{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null){
double longitude = location.getLongitude();
double latitude = location.getLatitude();
//Toast.makeText(getApplicationContext(), Double.toString(longitude), Toast.LENGTH_SHORT).show();
longval.setText(Double.toString(longitude));
latval.setText(Double.toString(latitude));
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
I am not sure when I put it into my phone (Galaxy Nexus). I saw a GPS icon on the bar located at the top of my phone. However, the textfield is not updated to show my current longitude and latitude. I would like to ask if it is the problem of my code or my phone? I am just switching on wifi without mobile data. It seems that onLocationChanged is not invoked.
Thanks everyone!
回答1:
Its difficult to get Lat,Long inside room/apartment using GPS.Instead of LocationManager.GPS_PROVIDER use LocationManager.NETWORK_PROVIDER..it ll solve ur problem.
回答2:
You Code is correct.After install it on your device change your current location at least 10 meter.We go from your current room to another room that is at least 10 meter away.I hope you will get your output....
来源:https://stackoverflow.com/questions/10716882/unable-to-get-longitude-and-latitude-in-android