android 获取当前定位
时间: 2023-07-11 13:52:49 浏览: 64
要获取当前位置,Android应用程序需要使用定位服务。以下是获取当前位置的步骤:
1. 检查应用程序是否具有获取位置信息的权限。如果没有权限,则需要请求用户授权。
2. 创建一个LocationManager对象,用于访问系统定位服务。
3. 创建一个LocationListener对象,用于接收位置更新。
4. 通过LocationManager对象注册LocationListener对象。
5. 启用位置更新。可以通过requestLocationUpdates()方法启用位置更新。该方法接受四个参数:位置提供者(GPS、网络或Passive),最小时间间隔(以毫秒为单位),最小距离(以米为单位)和LocationListener对象。
6. 在LocationListener对象的onLocationChanged()方法中处理位置更新。
下面是一个示例代码:
```java
// 检查权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
return;
}
// 获取LocationManager对象
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 创建LocationListener对象
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// 处理位置更新
double latitude = location.getLatitude();
double longitude = location.getLongitude();
// ...
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
};
// 注册LocationListener对象
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
// 启用位置更新
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
double latitude = lastKnownLocation.getLatitude();
double longitude = lastKnownLocation.getLongitude();
// ...
}
```