я постоянно получаю адрес, когда мой маркер перемещается на карту в течение одного раза. Если я перевожу свой маркер в Гуджарат (Индия), то он постоянно отображает всплывающее сообщение для этого местоположения, как мне его остановить?
Java-файл: открытый класс MainActivity расширяет FragmentActivity, реализует OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private GoogleMap mMap;
private boolean mLocationPermissionGranted = false;
private final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 101;
private FusedLocationProviderClient mFusedLocationClient;
private Location mLastKnownLocation,mChangeLocation=new Location("");
AddressResultReceiver mreceiver = null;
private GoogleMap.OnCameraIdleListener onCameraIdleListener;
private ImageView markerPin;
private Marker mCurrLocationMarker;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mFusedLocationClient = getFusedLocationProviderClient(this);
getLocationPermission();
mMap.setOnCameraIdleListener(onCameraIdleListener);
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
Task<Location> locationTask = mFusedLocationClient.getLastLocation();
locationTask.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location
if (location != null) {
mLastKnownLocation = location;
Log.d("result", mLastKnownLocation.toString());
setMarker(location);
}
}
});
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
private void configureCameraIdle() {
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
@Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
mChangeLocation.setLatitude(latLng.latitude);
mChangeLocation.setLongitude(latLng.longitude);
MarkerOptions markerOptions1=new MarkerOptions();
markerOptions1.position(latLng);
mMap.addMarker(markerOptions1);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
//mMap.addMarker(new MarkerOptions().position(latLng).title("new"));
startIntentService();
}
});
}
private void setMarker(Location location) {
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 100);
mMap.animateCamera(cameraUpdate);
configureCameraIdle();
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
}
void startIntentService() {
mreceiver = new AddressResultReceiver(new android.os.Handler());
Intent intent = new Intent(this, FetchAddressIntentService.class);
intent.putExtra(FetchAddressIntentService.Constants.RECEIVER, mreceiver);
intent.putExtra(FetchAddressIntentService.Constants.LOCATION_DATA_EXTRA, mChangeLocation);
startService(intent);
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
class AddressResultReceiver extends ResultReceiver
{
public AddressResultReceiver(Handler handler) {
super(handler);
}
protected void onReceiveResult(int resultCode, Bundle resultData) {
String mAddressOutput = resultData.getString(FetchAddressIntentService.Constants.RESULT_DATA_KEY);
Log.i("address", mAddressOutput);
//address.setText(mAddressOutput);
if (resultCode == FetchAddressIntentService.Constants.SUCCESS_RESULT) {
Toast.makeText(MainActivity.this,mAddressOutput,Toast.LENGTH_LONG).show();
/* Toast.makeText(LocationActivity.this, getString(R.string.address_found),
Toast.LENGTH_LONG).show();*/
}
}
}
}
FetchAddressIntentService.java 100 * * InventService.java: * 10081010 *
ResultReceiver myReciever;
public FetchAddressIntentService(){
super("Fetching address");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
String errorMessage = "";
//Get the location passed to this serviec thorugh an extra
Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
myReciever=intent.getParcelableExtra(Constants.RECEIVER);
List<Address> address = null;
try{
address = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
Toast.makeText(this,address.get(0).getAddressLine(0).toString(),Toast.LENGTH_LONG).show();
}
catch(Exception e){
Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();
}
//Handle the case when there is no location found
if(address == null || address.size() == 0){
Toast.makeText(this, "No address found", Toast.LENGTH_LONG).show();
deliverResulttoReciever(Constants.FAILURE_RESULT,"No address Found");
}
else{
Address currentAddress = address.get(0);
ArrayList<String> addressFragment = new ArrayList<String>();
//Fetch the address lines using getAddressLine
//join them and send them to the thread
for(int i = 0;i<=currentAddress.getMaxAddressLineIndex();i++)
{
addressFragment.add(currentAddress.getAddressLine(i));
}
deliverResulttoReciever(Constants.SUCCESS_RESULT, TextUtils.join(System.getProperty("line.saparator"),addressFragment));
}
}
private void deliverResulttoReciever(int resultCode, String message) {
Bundle bundle = new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY,message);
myReciever.send(resultCode,bundle);
}
public final class Constants {
public static final int SUCCESS_RESULT = 0;
public static final int FAILURE_RESULT = 1;
public static final String PACKAGE_NAME =
"com.google.android.gms.location.sample.locationaddress";
public static final String RECEIVER = PACKAGE_NAME + ".RECEIVER";
public static final String RESULT_DATA_KEY = PACKAGE_NAME +
".RESULT_DATA_KEY";
public static final String LOCATION_DATA_EXTRA = PACKAGE_NAME +
".LOCATION_DATA_EXTRA";
}
}
Я постоянно получаю адрес, когда мой маркер перемещается на карту в течение одного раза. Если я переместу свой маркер в Гуджарат (Индия), то он продолжает отображать всплывающее сообщение для этого местоположения, какя остановил это?
LogCat:
I / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, ИндияI / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, ИндиI / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия I/ адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия I / адрес: Гуджарат 383317, Индия