调用 Intent 时如何保持 MainActivity 运行?

Posted

技术标签:

【中文标题】调用 Intent 时如何保持 MainActivity 运行?【英文标题】:How to keep a MainActivity running when an Intent is called? 【发布时间】:2018-05-11 02:23:42 【问题描述】:

我有一个代码,当我调用地图活动时,它会接收纬度和经度并显示在地图上,但是当我在地图上时,onLocationChange 不会运行,因此它不会显示位置该人仅移动第一个属性,我如何更改它以使其不断发送属性?

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 !


--------------------------地图活动-------- ----------------------

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

    


【问题讨论】:

【参考方案1】:

您是否考虑过将 MapActivity 实现为覆盖 MainActivity 并且可以按需使其可见的片段?

然后,您可以在 MapActivity 中实现一个方法,您可以从 onLocationChanged() 调用该方法,它使所有必要的东西都显示在片段上的当前位置。

看看Fragments

在您的 MapActivity 中,您可以声明类似

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

在 MainActivity 你声明

public class MapFragment extends AppCompatActivity implements View.OnClickListener, LocationListener, GpsStatus.Listener 
      private MapFragment mapFragment; 

      ...

在您的 onCreate() 方法中,您设置片段的视图

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

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

当你完成所有这些后,你可以在你的 onLocationChanged() 方法中调用你在 MapFragment 中声明的方法

@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


【讨论】:

【参考方案2】:

是的,您可以一次运行两个活动,甚至更多。您所要做的就是在后台运行它们,然后您就可以使用 Service

查看文档

android service documentation

虽然不是同时,但您也可以让活动与服务一起侦听,您可以尝试启动结果意图并在

中接收结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)  /** you receive the result here**/

在活动结果中接收意图是有效的,因为大多数语音搜索应用、条形码扫描仪和地图都使用这种方法

【讨论】:

以上是关于调用 Intent 时如何保持 MainActivity 运行?的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 Intent 调用另一个活动

使用 Intent.ACTION_PACKAGE_REMOVED 时如何查找已卸载的包名

Acitivity之Intent调用方法

上下文对象是啥意思,在调用intent方法时,要传入一个上下文对象,到底是啥意思⊙_⊙

Android activity间通讯几种方式

如何使用 QAndroidJniObject 从 Java 调用 Intent