我正在尝试使用LocationManager和LocationListener获取用户的当前位置。但没有任何价值。
以下是我在Java中使用的代码:
// activity is implementing LocationListener
private LocationManager locationManager;
// in onCreate() method.
locationManager = (LocationManager) getSystemService(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) {
requestLocationPermission();
return;
}
else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
//outside onCreate()
@Override
public void onLocationChanged(Location location) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
NavProfileLocation.setText(String.valueOf(longitude)+" AND "+String.valueOf(latitude));
Toast.makeText(MainActivity.this,String.valueOf(longitude)+" AND "+String.valueOf(latitude),Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
我想使用当前用户的GPS获取纬度和经度。
答案 0 :(得分:1)
再添加一个权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
来自android doc api的最新更新: 检查网络和位置提供商。
private FusedLocationProviderClient fusedLocationClient;
// ..
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});