Copy codeThe Code is as follows: // declare the LocationManager object
LocationManager loctionManager;
// Obtain the LocationManager object through system services
LoctionManager = (LocationManager) getSystemService (Context. LOCATION_SERVICE );
Method 1:Copy codeThe Code is as follows: // obtain the location through the GPS location provider
String providerGPS = LocationManager. GPS_PROVIDER;
Location location = loctionManager. getLastKnownLocation (providerGPS );
Method 2:Copy codeThe Code is as follows: // obtain the location through the base station location provider
String providerNetwork = LocationManager. NETWORK_PROVIDER;
Location location = loctionManager. getLastKnownLocation (providerNetwork );
Method 3:Copy codeThe Code is as follows: // use a standard set to enable the system to automatically select the best available location provider and provide the location
Criteria criteria = new Criteria ();
Criteria. setAccuracy (Criteria. ACCURACY_FINE); // High Precision
Criteria. setAltitudeRequired (false); // altitude not required
Criteria. setBearingRequired (false); // orientation not required
Criteria. setCostAllowed (true); // cost allowed
Criteria. setPowerRequirement (Criteria. POWER_LOW); // Low Power Consumption
// From the available locations, the best providers' matching the above standards
String provider = loctionManager. getBestProvider (criteria, true );
// Obtain the location of the last change
Location location = loctionManager. getLastKnownLocation (provider );
Processing:Copy codeThe Code is as follows: // It is displayed in EditText.
UpdateWithNewLocation (location );
// Listen for location changes, once every 2 seconds, more than 10 meters away
LoctionManager. requestLocationUpdates (provider, 1000, 1, locationListener );
Listener and display:Copy codeThe Code is as follows: // location listener
Private final LocationListener locationListener = new LocationListener (){
@ Override
Public void onStatusChanged (String provider, int status, Bundle extras ){
}
@ Override
Public void onProviderEnabled (String provider ){
}
@ Override
Public void onProviderDisabled (String provider ){
}
// Triggered when the position changes
@ Override
Public void onLocationChanged (Location location ){
// Update TextView display with the new location
UpdateWithNewLocation (location );
}
};
Private void updateWithNewLocation (Location location ){
If (location! = Null ){
Double lat = location. getLatitude ();
Double lng = location. getlong.pdf ();
LatStr = format. format (lat );
LonStr = format. format (lng );
TxtLat. setText (latStr );
TxtLon. setText (lonStr );
} Else {
TxtLat. setText ("");
TxtLon. setText ("");
}
}