如何获取用户在android上的当前位置?
问题描述:
我一直在尝试使用融合位置API来获取用户的位置,完全像这里所描述的https://developer.android.com/training/location/retrieve-current.html 但我没有得到任何结果。有时它可以工作,但大多数情况下它不工作,并且这只是在虚拟设备上,真正的设备上没有发生。 这里是我的MainActivity.java:如何获取用户在android上的当前位置?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
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
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
10);
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
10);
// 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;
}
Log.v("","the beg");
mFusedLocationClient.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) {
// ...
Log.v("", String.valueOf(location.getLatitude()));
Log.v("", String.valueOf(location.getLongitude()));
}
}
});
Log.v("","the end");
}
} 这我Android.m
答
首先,定义一个LocationListener的处理位置的变化。
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
//your code here
}
};
然后得到的LocationManager,并要求位置更新
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
}
最后请确保您所添加的权限的清单,
对于使用基于唯一的网络位置使用一个
对于基于GPS的位置,这一个
@hassanitohajj in'onSucces'方法你有这个吗? if(location!= null)Geocoder geoCoder = new Geocoder(getBaseContext(),Locale.getDefault());''你有一些'...'因此我只是在问。 –