首先启用Ur GPS。
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
public static double lontitube,latitude;
protected LocationManager locationManager;
protected Location currentLocation;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
}
protected void performReverseGeocodingInBackground() {
showCurrentLocation();
}
protected void showCurrentLocation() {
currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (currentLocation != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
currentLocation.getLongitude(), currentLocation.getLatitude()
);
lontitube=currentLocation.getLongitude();
latitude=currentLocation.getLatitude();
System.out.println("----lati----longi----"+latitude+"\n"+lontitube);
Toast.makeText(Demo.this, message,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(Demo.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(Demo.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(Demo.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(Demo.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
在 AndroidManifest 添加
ACCESS_FINE_LOCATION
GPS 使用许可。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />