在 Android 中,可以使用 LocationManager 类来进行定位。下面是一个示例代码,演示如何获取当前位置:
```java
// 获取定位管理器
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 检查是否有定位权限
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 如果没有定位权限,请求定位权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
return;
}
// 获取最新的位置
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// 定义位置
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// 当位置发生变化时回调
double latitude = location.getLatitude();
double longitude = location.getLongitude();
// 处理新的位置信息
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {}
@Override
public void onProviderEnabled(String s) {}
@Override
public void onProviderDisabled(String s) {}
};
// 注册位置
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
```
在上述代码中,通过获取 LocationManager 实例,然后使用 getLastKnownLocation() 方法来获取最新的位置信息。如果没有定位权限,则需要申请权限。然后通过注册 LocationListener 来位置的变化。在回调函数 onLocationChanged() 中可以处理新的位置信息。可以根据需要选择使用 GPS_PROVIDER 还是 NETWORK_PROVIDER 来获取定位信息。