使用LocationManager和LocationListener结合进行简单定位功能
1.创建LocationManager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
2.创建LocationListener
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location != null) {
//经度
double longitude = location.getLongitude();
//纬度
double latitude = location.getLatitude();
} else {
if (locationIndex >= 0) {
final String errorMessage = "定位失败,请重新定位";
}
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
3.绑定
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
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;
}
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
}