要配置Android原生定位服務LocationManager,首先需要在AndroidManifest.xml文件中添加以下權限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
接著在代碼中獲取LocationManager實例并配置定位參數,例如:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
然后可以通過LocationManager注冊監聽器來獲取位置更新:
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//處理位置更新
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
最后不要忘記在適當時候停止定位服務:
locationManager.removeUpdates(locationListener);
以上就是配置Android原生定位服務LocationManager的基本步驟。根據實際需求,可以進一步配置定位參數和優化定位精度。