Command to update the location of the following code in 2 seconds:

Asked

Viewed 129 times

0

I’m developing an app and I need it to always update its location within a time frame. I found in this same site the following solution to take the location and turn into a marker as well as the camera goes to that location:

1 answer

1

First you have to implement the class LocationListener then implement the method

@Override
    public void onLocationChanged(Location location) {
}

here is where you will see your location changing every 2 seconds

then do location updates

@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);
}

where LOCATION_REFRESH_TIME is the time in milliseconds and LOCATION_REFRESH_DISTANCE in metres

don’t forget to add to the manifest

if you are using wi-fi

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 

or/and then if you are using GPS

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

for the user I re-edited my reply

 import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
 OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{

    /**
     * Mapa da aplicação
     */
    private GoogleMap mMap;

    /**
     * Responsável por disponibilizar a localização do smartphone.smartphone
     */
    private GoogleApiClient mGoogleApiClient;

    /**
     * Guarda a ultima posição do smartphone.
     */
    private Location mLastLocation;

    private LocationManager mLocationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000,
            0, mLocationListener);

        // Vamos instanciar o GoogleApiClient, caso seja nulo
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this) // Interface ConnectionCallbacks
                    .addOnConnectionFailedListener(this) //Interface OnConnectionFailedListener
                    .addApi(LocationServices.API) // Vamos a API do LocationServices
                    .build();
        }
    }
    /*
     * Ao iniciar, connectamos !
     */
    protected void onStart() {
        mGoogleApiClient.connect();
        super.onStart();
    }

    /*
      * Ao finalizar, desconectamos!
     */
    protected void onStop() {
        mGoogleApiClient.disconnect();
        super.onStop();
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    }



    /*
     * Método invocado quando o GoogleApiClient conseguir se conectar
     */
    @Override
    public void onConnected(Bundle bundle) {
        // pegamos a ultima localização
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            if(mMap != null){
                // Criamos o LatLng através do Location
                final LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                // Adicionamos um Marker com a posição...
                mMap.addMarker(new MarkerOptions().position(latLng).title("Minha Posição"));
                // Um zoom no mapa para a seua posição atual...
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));

            }

        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    /*
     * Neste método você deverá tratar caso não consiga se conncetar...
     */
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }


    @Override
    public void onLocationChanged(Location location) {
                //aqui vais conseguir ver a tua nova localização pela variavel "location"
                Toast.makeText(this, "upadte", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}
  • I really appreciate the help, but could you insert this code into mine? Because I don’t quite understand how I’m going to add this to my code.

  • I think just do what I have there, add these lines in your Oncreate, you have to define the variable mLocationManager clear then implement the Locationlistener it will ask you to implement the methods, add in the manifest these permissions, then LOCATION_REFRESH_TIME = 2000 and LOCATION_REFRESH_DISTANCE = 0. So you think you can do it yourself?

  • Actually no! kk I’m a beginner and if you help me would be eternally grateful! kkk

  • @Alanbarros see there if that’s what you want. I haven’t tested but I think that’s it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.