1

Ich habe einen Code, der, wenn ich die Kartenaktivität anrufe, die Breite und Länge empfängt und auf der Karte anzeigt, aber wenn ich auf der Karte bin, wird onLocationChange nicht ausgeführt, also zeigt es den Ort nicht an, wenn die Person ist Bewegen nur die ersten atributtes, wie ändere ich das, um es die atributtes ständig senden zu lassen?Wie kann eine MainActivity beim Aufruf einer Intent ausgeführt werden?

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 ! 

} 

------------------------------------- KARTENAKTIVITÄT ---- ---------------------------

import android.support.v4.app.FragmentActivity; 
import android.os.Bundle; 
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 { 

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

    } 

} 

Antwort

0

Ja, Sie können zwei Aktivitäten auf einmal und noch mehr ausführen. Alles, was Sie tun müssen, ist sie im Hintergrund laufen und Sie Dienst chack aus der Dokumentation bei

android service documentation

althoug nicht gleichzeitig verwenden können, aber Sie können auch die Aktivitäten hören mit dem Service lassen, Sie können versuchen, eine Absichtserklärung für Ergebnis zu starten und das Ergebnis in den

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { /** you receive the result here**/} 

receiveing ​​die Absicht in auf Aktivitätsergebnis ist effizient, da die meisten Stimme searc erhalten h app, barcode scanner und map verwenden diese methode

1

Haben Sie überlegt, die MapActivity als ein Fragment zu implementieren, das Ihre MainActivity abdeckt und das Sie bei Bedarf sichtbar machen können?

Sie können dann eine Methode in Ihrer MapActivity implementieren, die Sie von onLocationChanged() aufrufen und die alle notwendigen Schritte zum Anzeigen der aktuellen Position des Fragments ausführt.

Werfen Sie einen Blick auf Fragments

In Ihrem MapActivity Sie dann so etwas wie

public void locationChanged(double latitude, double longtitude){ 
    this.latitude = latitude; 
    this.longtitude = longtitude 
    //All necessary code you need to update the location shown on the map 
} 

In MainActivity

Sie erklären erklären können
public class MapFragment extends AppCompatActivity implements View.OnClickListener, LocationListener, GpsStatus.Listener { 
     private MapFragment mapFragment; 

     ... 
} 

In Ihrem onCreate() Methode setzen Sie die Ansicht des Fragments

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

     mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment); 
} 

Wenn Sie all das tat können Sie die Methode rufen Sie in MapFragment in Ihrem OnLocationChanged() Methode deklariert

@Override 
public void onLocationChanged(Location location) { 
     TextView coords=(TextView)findViewById(R.id.text_view_coords); 

     mapFragment.locationChanged(location.getLatitude(), location.getLongitude(); 

     //Rest of your code as necessary 

} 
Verwandte Themen