How to keep Mainactivity "feeding" map Activity?

Asked

Viewed 146 times

0

I have this code and at the moment I need to pass a latitude and longitude to receive on the map and show the current position the user is in, the problem is that when passing to the Intent of the map the onLocationChanged stops being executed and does not update the position, only returning to the MainActivity it runs again by updating the coordinates.

I would like to know how to leave this activity constantly updating the other activity, so having a GPS in real time shown on the map.

import android.content.pm.PackageManager;

import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.Manifest;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.model.LatLng;


public class MainActivity extends AppCompatActivity 
    implements View.OnClickListener, LocationListener, GpsStatus.Listener {

    private LocationManager locManager; //Gerente de Localização
    private LocationProvider locProvider; //Provedor de Localização
    private static final int REQUEST_LOCATION = 2; //Utilizado nas requisições de localização
    Intent map;
    LatLng Local;

    //Inicializado aqui para não dar crash caso o mapa seja 
    //chamado antes desses atributos serem inicializados.
    double latitude = 0;
    double longitude = 0;

    //Pacote onde será armazenado o valor do LatLng.
    Bundle args = new Bundle();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Instância dos buttons:
        Button map = (Button)findViewById(R.id.button_map);
        map.setOnClickListener(this);

        Button gnss = (Button)findViewById(R.id.button_gnss);
        gnss.setOnClickListener(this);

        Button config = (Button)findViewById(R.id.button_config);
        config.setOnClickListener(this);

        Button credits = (Button)findViewById(R.id.button_credits);
        credits.setOnClickListener(this);
        //Fim Instância dos Buttons

        //O Gerente recebe uma location
        locManager = (LocationManager)getSystemService(LOCATION_SERVICE);


    }

    @Override
    public void onClick(View view){
        switch(view.getId()){
            case R.id.button_map:
                Local = new LatLng(latitude, longitude);
                //Pacote inicializado com o LatLng
                args.putParcelable("Latlng", Local);

                //Criar tela relativa ao mapa
                map = new Intent(this, MapsActivity.class);
                //O pacote é passado para a Intent referente ao mapa
                map.putExtra("bundle", args);
                startActivity(map);

                break;

            case R.id.button_gnss:
               /*Intent gnss = new Intent(this, GnssActivity.class);
                startActivity(gnss);
                */
                break;

            case R.id.button_config:
                Intent config = new Intent(this, SettingsActivity.class);
                startActivity(config);

                break;

            case R.id.button_credits:
                Intent credits = new Intent(this, CreditsActivity.class);
                startActivity(credits);
                break;
        }

    }


    @Override
    protected void onResume(){
        super.onResume();
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED) {
            // A permissão foi dada
            ativaGPS();
        }
        else {
            // Solicite a permissão
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        desativaGPS();
    }


    public void onRequestPermissionsResult(int requestCode, 
            String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_LOCATION) {
            if(grantResults.length == 1 && grantResults[0] ==
                    PackageManager.PERMISSION_GRANTED) {
                // O usuário acabou de dar a permissão
                ativaGPS();
            }
            else {
                // O usuário não deu a permissão solicitada
                Toast.makeText(this, "Sua localização não será mostrada",
                    Toast.LENGTH_SHORT).show();
                        finish();
            }
        }
    }

    //Ativa o GPS
    public void ativaGPS() {
        try {
            locProvider = locManager.getProvider(LocationManager.GPS_PROVIDER);
            locManager.requestLocationUpdates(locProvider.getName(), 30000, 1, this);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    //Desativa o GPS
    public void desativaGPS() {
        try {
            locManager.removeUpdates(this);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    public void onGpsStatusChanged(int event) {
        // Alguma mudança no sistema GPS
        // A aplicação deverá chamar o método da classe LocationManager para 
        // obter   informações sobre o status do distema GPS.
        TextView coords=(TextView)findViewById(R.id.text_view_coords);
        String satInfo="PRN;Azimute;Elevação;SNR;Used in Fix\n";

        try {
            GpsStatus gpsStatus=locManager.getGpsStatus(null);
        } catch (SecurityException e) {
            e.printStackTrace();
        }

        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED) {
                    GpsStatus gpsStatus = locManager.getGpsStatus(null);
                    Iterable<GpsSatellite> sats=gpsStatus.getSatellites();
                     for (GpsSatellite sat:sats) {
                        // processe as informações de cada satélite
                     }
                }
        // Informações do sistema estão encapsuladas no objeto gpsStatus

        // Alguma mudança no sistema GPS

        // Informações do sistema estão encapsuladas no objeto gpsStatus


    }

    //Métodos criados automaticamente na implementação do Location Listener !
    @Override
    public void onLocationChanged(Location location) {
        TextView coords=(TextView)findViewById(R.id.text_view_coords);

        latitude=location.getLatitude();
        longitude=location.getLongitude();

        //Cordenadas em DD
        coords.setText("Latitude"+latitude +"\n"+"Longitude:"+longitude);

        /*coords.setText("Latitude:"+Location.convert(latitude,Location.FORMAT_SECONDS)
                +"\n" +
                "Longitude:"+Location.convert(longitude,Location.FORMAT_SECONDS)); */



        //Passar o Bundle referente ao LatLng criado anteriormente.


    }

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

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
    // FIM dos Métodos criados automaticamente na implementação do Location Listener !

}

-----------------------------MAP ACTIVITY--------------------------------------

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    double latitude;
    double longitude;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        Bundle bundle = getIntent().getParcelableExtra("bundle");

        LatLng objLatLng = bundle.getParcelable("Latlng");
        latitude = objLatLng.latitude;
        longitude= objLatLng.longitude;


        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        float zoomLevel = 16.0f;
        mMap = googleMap;

        //Posição atual marcada no mapa referentes a marcação e setagem da 
        //posição atual na API do Google Maps
        LatLng posAtual = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(posAtual).title("Sua posição atual!"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(posAtual));

        //This goes up to 21
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(posAtual, zoomLevel));

    }

}

1 answer

0


In his MainActivity you are calling the method desativaGPS() within the onPause(). You could call him inside the onDestroy().

UPDATING

For your MainActivity constantly update your MapActivity you have two ways of doing this:

  1. Create a BaseActivity - a generic Activity in the case - which is responsible for performing all the functions relating to the location you have implemented in the MainActivity. So this last one and the MapActivity would inherit from the BaseActivity and therefore would be able to get localization updates.
  2. Launching a broadcast every update of the MainActivity, that would be intercepted by MapActivity, by obtaining location data through the Intent. As I let down.

Mainactivity.java

//Métodos criados automaticamente na implementação do Location Listener !
@Override
public void onLocationChanged(Location location) {
    ...

    // Envia um broadcast a cada atualização com a localização
    Intent i = new Intent("LOCATION_UPDATED");
    i.putExtra("location", location);
    LocalBroadcastManager.getInstance(this).sendBroadcast(i);
}

Mapactivity.java

private BroadcastReceiver locationUpdatedReceiver;

@Override
protected void onStart() {
    super.onStart();
    if (locationUpdatedReceiver == null) {
        locationUpdatedReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // Obtém a localização passada pela intent
                Location location = intent.getExtras().getParcelable("location");
                // TODO: Realiza a atualização do mapa aqui
            }
        };
    }
    // Cria um filtro para o broadcast.
    // No caso, é definida que toda a Intent com a action "LOCATION_UPDATED",
    // vai chamar esse BroadcastReceiver
    IntentFilter intentFilter = new IntentFilter("LOCATION_UPDATED");
    LocalBroadcastManager.getInstance(this)
            .registerReceiver(locationUpdatedReceiver, intentFilter);
}

@Override
protected void onStop() {
    super.onStop();
    // "Desregistra" o receiver para que não seja atualizada sua activity
    // desnecessariamente com o usuário fora dela. Mas você é quem decide        
    // se quer fazer isso no onStop(). Dá pra fazer no onDestroy() também.
    LocalBroadcastManager.getInstance(this)
            .unregisterReceiver(locationUpdatedReceiver);
}
  • it’s true, I didn’t realize it, I’ll test it here, ty

  • unfortunately it did not work, the gps is still on but the information is not passed

  • Thank you very much, it worked perfectly, although there are still some bugs that this implementation causes, such as an excessive delay to load the map, and when I leave the map related activity when I try to get back to it the map does not load in any way, but it keeps being updated while running

  • Which of the two ways you used?

  • I used Broadcast

Browser other questions tagged

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