Android 获取位置信息(经纬度)(附代码)

        获取位置信息主要通过GPS和网络位置两种方法,优先级还是GPS,有点就不多说了,下面说一下我做的方法及附代码,有疑问可在下方留言。

       思路便是GPS优先,但在GPS信号弱的情况下采取拿网络位置来弥补的方法,尽量做到次次上传都有位置信息传上去。

      

private String getLngAndLat(Context context) {

    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  //从gps获取经纬度
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        } else {//当GPS信号弱没获取到位置的时候又从网络获取
            return getLngAndLatWithNetwork();
        }
    } else {    //从网络获取经纬度
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }
    return longitude + "," + latitude;
}

//从网络获取经纬度
public String getLngAndLatWithNetwork() {
    double latitude = 0.0;
    double longitude = 0.0;
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    }
    return longitude + "," + latitude;
}

你可能感兴趣的:(Android)