今天在Android项目中要实现一个通过GPS或NetWork来获取当前移动终端设备的经纬度功能。要实现该功能要用到Android Framework 中的 LocationManager 类。下面我就直接贴上主要的代码说明如何实现通过GPS或NetWork来获取实时位置的经纬度。
private double latitude=0.0;
private double longitude =0.0;
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}else{
LocationListener locationListener = new LocationListener() {
// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
// Provider被enable时触发此函数,比如GPS被打开
@Override
public void onProviderEnabled(String provider) {
}
// Provider被disable时触发此函数,比如GPS被关闭
@Override
public void onProviderDisabled(String provider) {
}
//当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e("Map", "Location changed : Lat: "
+ location.getLatitude() + " Lng: "
+ location.getLongitude());
}
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 0,locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitude = location.getLatitude(); //经度
longitude = location.getLongitude(); //纬度
}
}
同时别忘了在AndroidManifest.xml文件中加入如下权限:
<!-- 连接互联网Internet权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GPS定位权限 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
文章出处: http://blog.csdn.net/cjjky/article/details/6557561