fengfeilong0529 / Android-Notes

Ask myself one question at least every day!
0 stars 1 forks source link

Android原生API获取经纬度等位置信息 #31

Open fengfeilong0529 opened 5 years ago

fengfeilong0529 commented 5 years ago

Purpose:通过GPS或NetWork来获取当前移动终端设备的经纬度功能

前提:设备需要带有GPS模块或NetWork模块;

参考: https://www.jianshu.com/p/e97d55262bd4 https://www.jianshu.com/p/05f85f2f74c1

实现:


/**
* 调用本地GPS来获取经纬度
* @param context
*/
private void getLocation(Context context) {
//1.获取位置管理器
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//2.获取位置提供器,GPS或是NetWork
List<String> providers = locationManager.getProviders(true);
if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
//如果是网络定位
locationProvider = LocationManager.NETWORK_PROVIDER;
} else if (providers.contains(LocationManager.GPS_PROVIDER)) {
//如果是GPS定位
locationProvider = LocationManager.GPS_PROVIDER;
} else if (providers.contains(LocationManager.PASSIVE_PROVIDER)) {
//如果是PASSIVE定位
locationProvider = LocationManager.PASSIVE_PROVIDER;
}
else {
Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
return;
}
//3.获取上次的位置,一般第一次运行,此值为null
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    // TODO: Consider calling
    //    ActivityCompat#requestPermissions
    // here to request the missing permissions, and then overriding
    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
    //                                          int[] grantResults)
    // to handle the case where the user grants the permission. See the documentation
    // for ActivityCompat#requestPermissions for more details.
    return;
}
Location location = locationManager.getLastKnownLocation(locationProvider);
if (location != null) {
    showLocation(location);
} else {
    // 监视地理位置变化,第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
    locationManager.requestLocationUpdates(locationProvider, MIN_TIME, MIN_DISTANCE, mListener);
}

}

LocationListener mListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { }

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onProviderDisabled(String provider) {
}

// 如果位置发生变化,重新显示
@Override
public void onLocationChanged(Location location) {
    showLocation(location);
}

};

/**