【发布时间】:2021-10-10 05:12:55
【问题描述】:
嘿,我的代码每时每刻都在请求位置,并且在 onLocationChanged 方法上,我有一个显示 GPS 地址的 toast,问题是 onLocationChanged 每时每刻都会被调用,而我不想每时每刻都需要位置的 Toast,因为我最终收到了 Toasts 的垃圾邮件,有没有办法将其更改为对用户更好的东西?
public void onLocationChanged(Location location) {
mMap.clear();
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
Context context;
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (listAddresses != null && listAddresses.size() > 0)
{
if (listAddresses.get(0).getThoroughfare() != null)
{
address += listAddresses.get(0).getThoroughfare() + " ";
}
if (listAddresses.get(0).getLocality() != null)
{
address += listAddresses.get(0).getLocality() + " ";
}
if (listAddresses.get(0).getPostalCode() != null)
{
address += listAddresses.get(0).getPostalCode() + " ";
}
if (listAddresses.get(0).getAdminArea() != null)
{
address += listAddresses.get(0).getAdminArea();
}
Toast.makeText(MapAcvitiy.this, address, Toast.LENGTH_SHORT).show();
Log.i("Address", address);
}
} catch (IOException e) {
e.printStackTrace();
}
}
我的代码的另一部分是创建 locationManager 并设置 requestLocationUpdates 以随时请求位置。
if (Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},1);
}else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.clear();
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}
}
【问题讨论】:
标签: java android android-studio google-maps-markers