AndroidManifest.xml 增加 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
public class ditu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String serviceName=Context.LOCATION_SERVICE;
locationManager=(LocationManager)this.getSystemService(serviceName);
//查詢條件
Criteria criteria=new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider=locationManager.getBestProvider(criteria,true);
Location location=locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
//設(shè)置監(jiān)聽器,自動更新的最小時(shí)間為間隔1秒,最小位移變化超過5米
locationManager.requestLocationUpdates(provider, 1000, 5, locationListener);
}
private final LocationListener locationListener=new LocationListener(){
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location){
String latLongString;
TextView myLocationText;
myLocationText=(TextView)this.findViewById(R.id.myLocationText);
if(location!=null){
double lat=location.getLatitude();
double lng=location.getLongitude();
latLongString="維度:"+lat+"\n經(jīng)度"+lng;
}else{
latLongString="無法獲取地理信息";
}
myLocationText.setText("您所在位置為:"+latLongString);
}
}
哈哈,只要手機(jī)開了GPS,你就能隨時(shí)定位自己的位置,可惜顯示出來的是經(jīng)緯度,如果結(jié)合google API,那就能顯示在地圖上了。