Android获取地理位置信息(GPS/NETWORK)

安卓给我们提供了一个LocationManager.java类(文件位于framework/base/locaiton/java/android/location/LocationManager.java)

我们可以直接使用,使用方法如下:
 

    private Location getLocation(){
        android.location.LocationManager locationManager = (android.location.LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location [] locations = new Location[2];
        String providerGPS = android.location.LocationManager.GPS_PROVIDER;
        String providerNetwork = android.location.LocationManager.NETWORK_PROVIDER;
        locations[0] = locationManager.getLastKnownLocation(providerGPS);
        locations[1] = locationManager.getLastKnownLocation(providerNetwork);

        Location currentLocation = null;
        for (int i = 0; i < locations.length; i++) {
            Location l = locations[i];
            if (l != null) return l;
        }
        return null;
    }

这里我们同时使用GPS和Network来定位,优先使用GPS,当无法使用GPS获取时,使用Network定位。两者都获取不到地理位置信息时,返回null

你可能感兴趣的:(Android获取地理位置信息(GPS/NETWORK))