如何使用自己的活动布局来制作两个不同的地图活动

时间:2019-06-21 15:27:04

标签: java android google-maps

我正在尝试创建两个名为 TrainMapsActivity.java 的地图活动,其自身的活动布局为 activity_maps_train.xml activity_maps_bus.xml

这个想法是为公共汽车和火车准备单独的地图。公交地图将拥有自己的车站和公交车,而火车地图也是如此...至少这是计划。我已经用TrainMapsActivity和activity_maps_train.xml做到了这一点,其工作原理与我的到达时间计算应用程序(学校项目)相同。

现在的问题是当我尝试进行两次地图活动时。

到目前为止我尝试过的

到目前为止,我已经通过谷歌搜索尝试了不同的方法,但是有些方法没有用,而另一些我不了解(我仍然是Android应用程序开发的新手)

示例为:

1。尝试杀死活动,认为第一个MapsActivity在进入下一个活动时正在使用某些过程

//in the MainActivity.class
Intent intent = new Intent(this, TrainMapsActiviy.class); 
startActivity(intent);
finish();

//in the TrainMapsActivity.class
    @Override
     public void onBackPressed() {
           super.onBackPressed();
           this.finish();
     }

但这只会杀死整个应用程序

2。尝试了另一种方法,即在转到另一个活动(activity_maps_bus)之前先杀死该活动(activity_maps_train.xml)。

//in the MainActivity.class
Intent intent = new Intent(MainActivity.this, TrainMapsActivity.class);
startActivity(intent);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

当我尝试打开activity_maps_bus时,应用仍然崩溃

  1. 我尝试使用多个地图片段来完成此操作,如这篇帖子best practice for multiple maps中所建议的那样? 但我无法一次掌握两个碎片的概念

示例代码:

TrainMapsActivity.java

    import ... //All my imports


    public class TrainMapsActivity extends FragmentActivity implements 
    OnMapReadyCallback, View.OnClickListener, 
    GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener, 
    com.google.android.gms.location.LocationListener {

    private GoogleMap mMap;
    private LatLng stationA = new LatLng(9.016296,38.789405);
    private LatLng StationB = new LatLng(9.014914,38.783268);
    private LatLng TrainA = new LatLng(9.019681, 38.802726);

    private static final String TAG = "TrainMapsActivity";
    private TextView mLatitudeTextView;
    private TextView mLongitudeTextView;
    private GoogleApiClient mGoogleApiClient;
    private Location mLocation;
    private LocationManager mLocationManager;
    private LocationRequest mLocationRequest;
    private com.google.android.gms.location.LocationListener listener;
    private LocationManager locationManager;
    private LatLng latLng;
    private long UPDATE_INTERVAL = 2 * 4000;  /* 40 secs */
    private long FASTEST_INTERVAL = 50000; /* 50 sec */
    private boolean isPermission;

    private List<Marker> markList = new ArrayList<>();
    double backup;

    Button btnHit;
    ImageButton currentLocationIB;
    ProgressDialog pd;

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

        btnHit = findViewById(R.id.btnHit);

        if (requestSinglePermission()) {
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);

            mLatitudeTextView = findViewById((R.id.latitude_textview));
            mLongitudeTextView = findViewById((R.id.longitude_textview));

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();

            mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

            checkLocation();

        }
    }

    Marker markerName;

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setTrafficEnabled(true);

        if (latLng != null) {

            Circle circle = mMap.addCircle(new CircleOptions()
                    .center(latLng)
                    .radius(1600)     //The radius of the circle, specified in meters. It should be zero or greater.
                    .strokeColor(Color.rgb(0, 136, 255))
                    .fillColor(Color.argb(40, 216, 46, 0)));

            markerName = mMap.addMarker(new MarkerOptions().position(latLng).title("Current Location"));
            h++;

            currentLocationIB = findViewById((R.id.currentLocationImageButton));
            currentLocationIB.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
                }
            });


        }

        Button mybtn = findViewById(R.id.btn1);
        mybtn.setOnClickListener(this);

        backup=distance;

        }
    }

    public void arrival (View v) {
          //Calulates arrival time

    }

    private class getURL extends AsyncTask<String, String, String> {

        //Parses the out put from DistanceMarixAPI 
    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        startLocationUpdates();

        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (mLocation == null) {
            startLocationUpdates();
        }
        if (mLocation != null) {

            // mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
            //mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
        } else {
            Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection Suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
    }

    @Override
    public void onLocationChanged(Location location) {
        latLng = new LatLng(location.getLatitude(), location.getLongitude());
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    protected void startLocationUpdates() {
        // Create the location request
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setFastestInterval(FASTEST_INTERVAL);
        // Request location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
        Log.d("reque", "--->>>>");
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    private boolean checkLocation() {
        if (!isLocationEnabled())
            showAlert();
        return isLocationEnabled();
    }


    private boolean isLocationEnabled() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }

    private boolean requestSinglePermission() {
          //gets permission from user
     }

    }

BusMapsActivity.java

    import ... //All my imports


    public class TrainMapsActivity extends FragmentActivity implements 
    OnMapReadyCallback, View.OnClickListener, 
    GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener, 
    com.google.android.gms.location.LocationListener {

    private GoogleMap mMap;
    private LatLng stationA = new LatLng(9.016296,38.789405);
    private LatLng StationB = new LatLng(9.014914,38.783268);
    private LatLng BusA = new LatLng(9.019681, 38.802726);

    private static final String TAG = "BusMapsActivity";
    private TextView mLatitudeTextView;
    private TextView mLongitudeTextView;
    private GoogleApiClient mGoogleApiClient;
    private Location mLocation;
    private LocationManager mLocationManager;
    private LocationRequest mLocationRequest;
    private com.google.android.gms.location.LocationListener listener;
    private LocationManager locationManager;
    private LatLng latLng;
    private long UPDATE_INTERVAL = 2 * 4000;  /* 40 secs */
    private long FASTEST_INTERVAL = 50000; /* 50 sec */
    private boolean isPermission;

    private List<Marker> markList = new ArrayList<>();
    double backup;

    Button btnHit;
    ImageButton currentLocationIB;
    ProgressDialog pd;

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

        btnHit = findViewById(R.id.btnHit2);

        if (requestSinglePermission()) {
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map2);
            mapFragment.getMapAsync(this);

            mLatitudeTextView = findViewById((R.id.latitude_textview));
            mLongitudeTextView = findViewById((R.id.longitude_textview));

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();

            mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

            checkLocation();

        }
    }

    Marker markerName;

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setTrafficEnabled(true);

        if (latLng != null) {

            Circle circle = mMap.addCircle(new CircleOptions()
                    .center(latLng)
                    .radius(1600)     //The radius of the circle, specified in meters. It should be zero or greater.
                    .strokeColor(Color.rgb(0, 136, 255))
                    .fillColor(Color.argb(40, 216, 46, 0)));

            markerName = mMap.addMarker(new MarkerOptions().position(latLng).title("Current Location"));
            h++;

            currentLocationIB = findViewById((R.id.currentLocationImageButton));
            currentLocationIB.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
                }
            });


        }

        Button mybtn = findViewById(R.id.btn2);
        mybtn.setOnClickListener(this);

        backup=distance;

        }
    }

    public void arrival (View v) {
          //Calulates arrival time

    }

    private class getURL extends AsyncTask<String, String, String> {

        //Parses the out put from DistanceMarixAPI 
    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        startLocationUpdates();

        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (mLocation == null) {
            startLocationUpdates();
        }
        if (mLocation != null) {

            // mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
            //mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
        } else {
            Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection Suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
    }

    @Override
    public void onLocationChanged(Location location) {
        latLng = new LatLng(location.getLatitude(), location.getLongitude());
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map2);
        mapFragment.getMapAsync(this);
    }

    protected void startLocationUpdates() {
        // Create the location request
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setFastestInterval(FASTEST_INTERVAL);
        // Request location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
        Log.d("reque", "--->>>>");
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    }

MainActivity.java

    import ... //All my imports

    public class MainActivity extends AppCompatActivity {

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

        ImageView imgBus = findViewById(R.id.busIcon);
        imgBus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, BusMapsActivity.class));
            }
        });

        ImageView imgTrain = findViewById(R.id.trainIcon);
        imgTrain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, TrainMapsActivity.class);
                startActivity(intent);
            }
        });
     }
    }    

activity_map_train.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FC0"
    android:gravity="center|bottom" >

    <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp"
        map:mapType="normal" />

    <Button
        android:id="@+id/btnHit"
        android:layout_width="112dp"
        android:layout_height="59dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="25dp"
        android:layout_marginTop="446dp"
        android:layout_marginEnd="26dp"
        android:layout_marginBottom="13dp"
        android:background="#359c5e"
        android:text="Arrival Time"
        android:textColor="#ffffff"
        android:onClick="arrival"/>

    <ImageButton
        android:id="@+id/currentLocationImageButton"
        android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="6dp"
        android:layout_marginEnd="6dp"
        android:layout_marginBottom="520dp"
        android:contentDescription="@null"
        android:src="@drawable/current_location_vector_icon" />
</RelativeLayout>

activity_map_bus.xml

//the code is similar to activity_map_train.xml

那么,有人可以帮助我吗? 我的整体方法在这件事上是错误的吗,如果是的话,请引导我正确的方法。

我正在Windows 8.1上使用 Android Studio 3.0

另外请注意,打开TrainMapsActivity始终有效,当我尝试打开BusMapsActivity时,应用程序崩溃

谢谢,请原谅我的语法。

编辑:    我通过@Nikos Hidalgo找到了解决方案,他建议我看一下logcat并从日志中搜索BusMapsActivity。

原来,我的问题与帖子完全无关。但是,问题是我没有在AndroidManifest.xml中包含BusMapsActiviy

0 个答案:

没有答案