问题
I know same question is already asked here in 2016 but I tried those and they are not working at all. I tried Stop Location Updates after first time and I tried method that are told in this.
I want to stop location update once it get location. removeUpdate
is not working.
I had tried this code in onLocationChanged() method mLocationManager.removeUpdates(mListener);
but it never works. removeUpdate comes in red.
Please suggest me what should I do and plz watch my code and see what I have used and accordingly answer please.
Thank you in advance.
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private String lang,lat;
Double latitude;
Double longitude;
private Location mylocation;
private GoogleApiClient googleApiClient;
private GoogleMap mMap;
private final static int REQUEST_CHECK_SETTINGS_GPS=0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS=0x2;
@Override
public void onMapReady(GoogleMap googleMap) {
/*
LatLng currentLocation = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(currentLocation).title("Marker in Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
*/
mMap = googleMap;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpGClient();
}
private synchronized void setUpGClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0, this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
mylocation = location;
if (mylocation != null) {
latitude=mylocation.getLatitude();
longitude=mylocation.getLongitude();
String _lang = longitude + "";
String _lat = latitude + "";
Toast.makeText(this, "Longitude: " + _lang + "\nLatitude: " + _lat, Toast.LENGTH_LONG).show();
//Or Do whatever you want with your location
}
}
@Override
public void onConnected(Bundle bundle) {
checkPermissions();
}
@Override
public void onConnectionSuspended(int i) {
//Do whatever you need
//You can display a message here
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
//You can display a message here
}
private void getMyLocation(){
if(googleApiClient!=null) {
if (googleApiClient.isConnected()) {
int permissionLocation = ContextCompat.checkSelfPermission(MapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(30*1000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, this);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied.
// You can initialize location requests here.
int permissionLocation = ContextCompat
.checkSelfPermission(MapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15.5f));
}
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied.
// But could be fixed by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
// Ask to turn on GPS automatically
status.startResolutionForResult(MapsActivity.this,
REQUEST_CHECK_SETTINGS_GPS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied.
// However, we have no way
// to fix the
// settings so we won't show the dialog.
// finish();
break;
}
}
});
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CHECK_SETTINGS_GPS:
switch (resultCode) {
case Activity.RESULT_OK:
getMyLocation();
break;
case Activity.RESULT_CANCELED:
finish();
break;
}
break;
}
}
private void checkPermissions(){
int permissionLocation = ContextCompat.checkSelfPermission(MapsActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
}
}else{
getMyLocation();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
int permissionLocation = ContextCompat.checkSelfPermission(MapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
getMyLocation();
}
}
}
来源:https://stackoverflow.com/questions/62267166/how-to-stop-location-updates-in-google-map-api