生成APK与测试应用程序时,活动的奇怪行为

时间:2015-05-02 23:25:54

标签: android google-maps android-studio

所以我在我的应用程序中有这个代码,它使用" locationListenerFunc = new LocationListener"在应用程序未处于焦点时收集信息。服务, 然后当应用程序恢复焦点时,它使用此信息在地图上显示一条线, 当我测试应用程序并最小化它时,然后打开应用程序备份,一切正常,应用程序处于与我离开时相同的状态,并执行它想要做的所有事情。 当我生成APK并以这种方式测试时,它可以正常工作,但当我关闭它时,然后将其打开,它会重新启动itseld,活动与我离开时的状态不同。(进一步的测试表明,我恢复应用程序,它再次进入onCreate,而不是恢复)

有谁知道为什么会这样?

这是我的主要活动代码>

package -----;

import android.content.Context;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;
import java.util.List;

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private Button startTrackingButton;
    private Button stopTrackingButton;
    private TextView mainText;
    private Boolean isInPause = false;
    private List<LocationItems> locationItemsList = new ArrayList<LocationItems>();
    private double ladHistory = 0;
    private double logHistory = 0;
    private LocationManager manager;
    private LocationListener locationListenerFunc;

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

        //casting
        startTrackingButton = (Button) findViewById(R.id.BTStartTracking);
        stopTrackingButton = (Button) findViewById(R.id.BTStopTracking);
        mainText = (TextView) findViewById(R.id.TVMainTextView);

        stopTrackingButton.setEnabled(false);

        //GPS LOCATION MANAGER
        manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationListenerFunc = new LocationListener() {

            @Override
            public void onLocationChanged(Location location) {
                ///
                Log.d("myTag", "onlocation change ?");
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        new LatLng(location.getLatitude(), location.getLongitude()), 13));

                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                        .zoom(17)                   // Sets the zoom
                        .bearing(90)                // Sets the orientation of the camera to east
                        .tilt(30)                   // Sets the tilt of the camera to 30 degrees
                        .build();                   // Creates a CameraPosition from the builder
                mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                //sets text & lat, long>
                Time today = new Time(Time.getCurrentTimezone());
                today.setToNow();

                double Lad = location.getLatitude();
                double Long = location.getLongitude();
                mainText.setText("lat: " + String.valueOf(Lad) + ", " + "long: " + String.valueOf(Long) + ", last update at: " + today.format("%k:%M:%S"));


                //add a line on map
                if ((ladHistory != 0) && (logHistory != 0)) {

                    PolylineOptions line =
                            new PolylineOptions().add(new LatLng(ladHistory,
                                            logHistory),
                                    new LatLng(location.getLatitude(),
                                            location.getLongitude()))
                                    .width(30).color(Color.RED);

                    mMap.addPolyline(line);

                }


                //updates veraibles
                ladHistory = location.getLatitude();
                logHistory = location.getLongitude();

                //handles all polylines lost while application was offline:
                if (isInPause == true) {
                    locationItemsList.add(new LocationItems(location.getLatitude(), location.getLongitude()));
                }

                ///
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };


        //stops tracking button touch listener
        stopTrackingButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {

                //handles the disabling and starting of buttons
                stopTrackingButton.setEnabled(false);
                startTrackingButton.setEnabled(true);

                //removing locaion updates
                manager.removeUpdates(locationListenerFunc);
                manager = null;

                mainText.setText("stopped location update");

            }
        });

        //starts tracking button touch listener
        startTrackingButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                //Do stuff here
                Time today = new Time(Time.getCurrentTimezone());
                today.setToNow();

                mainText.setText("location update started at:  " + today.format("%k:%M:%S"));

                manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                        1000, 0, locationListenerFunc);


                //handles the disabling and starting of buttons
                startTrackingButton.setEnabled(false);
                stopTrackingButton.setEnabled(true);


            }
        });


        //setting up map
        setUpMapIfNeeded();


    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        isInPause = false;

        //repaints all lost points
        for (int i = 0; i < locationItemsList.size() - 1; i++) {

            LocationItems sourceItem = (LocationItems) locationItemsList.get(i);
            LocationItems destinationItem = (LocationItems) locationItemsList.get(i + 1);

            PolylineOptions line =
                    new PolylineOptions().add(new LatLng(sourceItem.getLatiduteVar(),
                                    sourceItem.getLongitudeVar()),
                            new LatLng(destinationItem.getLatiduteVar(),
                                    destinationItem.getLongitudeVar()))
                            .width(30).color(Color.RED);

            mMap.addPolyline(line);

            //zeroes the lists
            locationItemsList = new ArrayList<LocationItems>();

        }
    }

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

        isInPause = true;

    }

    protected void onDestroy() {
        super.onDestroy();

        manager.removeUpdates(locationListenerFunc);
        manager = null;

    }


    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                centerMapOnMyLocation(); //centers the map on user location
            }
        }
    }

    private void centerMapOnMyLocation() {

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));

        if (location != null) {

            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location.getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                    .zoom(17)                   // Sets the zoom
                    .bearing(90)                // Sets the orientation of the camera to east
                    .tilt(30)                   // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));


            //sets text >
            double Lad = location.getLatitude();
            double Long = location.getLongitude();
            mainText.setText("lat: " + String.valueOf(Lad) + ", " + "long: " + String.valueOf(Long));


        }

    }

}

这是我的清单文件&gt;

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="-----" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="-------" />

        <activity
            android:name=".MapsActivity"
            android:screenOrientation="portrait"
            android:label="@string/title_activity_maps" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

0 个答案:

没有答案