如何停止在谷歌地图android接收位置更新

时间:2016-04-19 06:33:30

标签: android google-maps location

我正在制作位置跟踪应用程序。 为此,我把两个按钮停止并启动,在启动按钮上单击接收位置更新启用, 在停止按钮上单击停止接收位置更新。

但停止接收位置更新无效。

                            package com.jaygandhi.tracking;


                    import android.Manifest;
                    import android.content.IntentSender;
                    import android.content.pm.PackageManager;
                    import android.location.Location;
                    import android.os.Bundle;
                    import android.support.v4.app.ActivityCompat;
                    import android.support.v4.app.FragmentActivity;
                    import android.support.v7.app.AppCompatActivity;
                    import android.util.Log;
                    import android.view.View;
                    import android.widget.Button;
                    import android.widget.Toast;

                    import com.google.android.gms.common.ConnectionResult;
                    import com.google.android.gms.common.GooglePlayServicesUtil;
                    import com.google.android.gms.common.api.GoogleApiClient;
                    import com.google.android.gms.location.LocationListener;
                    import com.google.android.gms.location.LocationRequest;
                    import com.google.android.gms.location.LocationServices;
                    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.LatLng;
                    import com.google.android.gms.maps.model.Marker;
                    import com.google.android.gms.maps.model.MarkerOptions;

                    public class MapsActivity extends FragmentActivity implements
                            GoogleApiClient.ConnectionCallbacks,
                            GoogleApiClient.OnConnectionFailedListener,
                            LocationListener {

                        private Button bStop, bStart;
                        private boolean mRequestLocationUpdates = false;
                        private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

                        public static final String TAG = MapsActivity.class.getSimpleName();

                        /*
                         * Define a request code to send to Google Play services
                         * This code is returned in Activity.onActivityResult
                         */
                        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

                        private GoogleMap mMap; // Might be null if Google Play services APK is not available.

                        private GoogleApiClient mGoogleApiClient;
                        private LocationRequest mLocationRequest;


                        Marker mCurrLocationMarker;

                        private static int UPDATE_INTERVAL = 5 * 1000;
                        private static int FATEST_INTERVAL = 1 * 1000;
                        private static int DISPLACEMENT = 10;


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

                            bStart = (Button) findViewById(R.id.btnstart);
                            bStop = (Button) findViewById(R.id.btnstop);


                            if (checkPlayServices()) {
                                buildGoogleApiClient();
                                createLocationRequest();
                            }

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

                            // Create the LocationRequest object
                            mLocationRequest = LocationRequest.create()
                                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                                    .setInterval(5 * 1000)        // 10 seconds, in milliseconds
                                    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

                    */

                            bStart.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //togglePeriodLocationUpdates();
                                    startLocationUpdates();
                                }
                            });

                            bStop.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //togglePeriodLocationUpdates();
                                    //stopLocationUpdates();
                                    stopLocationUpdates();
                                }
                            });
                        }

                        /*public void st()
                        {
                            mRequestLocationUpdates = true;

                            startLocationUpdates();
                        }

                        public void sp()
                        {

                            mRequestLocationUpdates = false;

                            stopLocationUpdates();
                        }
                    */
                        /*private void togglePeriodLocationUpdates()
                        {
                            if(!mRequestLocationUpdates)
                            {


                                mRequestLocationUpdates = true;

                                startLocationUpdates();
                            }

                            else
                            {


                                mRequestLocationUpdates = false;

                                stopLocationUpdates();
                            }
                        }*/

                        protected void startLocationUpdates() {
                            mRequestLocationUpdates = true;

                            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);


                            Log.d(TAG, String.valueOf(mRequestLocationUpdates));
                            //Log.d(TAG, String.valueOf(mGoogleApiClient));


                        }

                        protected void stopLocationUpdates()
                        {

                            mRequestLocationUpdates = false;
                            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

                            Log.d(TAG, String.valueOf(mRequestLocationUpdates));
                        }

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

                        @Override
                        protected void onResume()
                        {
                            super.onResume();
                            checkPlayServices();


                            //mGoogleApiClient.connect();

                            if(mGoogleApiClient.isConnected() )
                            {
                                if(mRequestLocationUpdates)
                                {
                                    startLocationUpdates();
                                    setUpMapIfNeeded();
                                }

                            }

                        }

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

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

                            if (mGoogleApiClient.isConnected())
                            {
                                stopLocationUpdates();
                            }
                        }

                        /**
                         * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
                         * installed) and the map has not already been instantiated.. This will ensure that we only ever
                         * call {@link #setUpMap()} once when {@link #mMap} is not null.
                         * <p/>
                         * If it isn't installed {@link SupportMapFragment} (and
                         * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
                         * install/update the Google Play services APK on their device.
                         * <p/>
                         * A user can return to this FragmentActivity after following the prompt and correctly
                         * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
                         * have been completely destroyed during this process (it is likely that it would only be
                         * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
                         * method in {@link #onResume()} to guarantee that it will be called.
                         */
                        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)
                                {
                                    setUpMap();
                                }
                            }
                        }

                        /**
                         * This is where we can add markers or lines, add listeners or move the camera. In this case, we
                         * just add a marker near Africa.
                         * <p/>
                         * This should only be called once and when we are sure that {@link #mMap} is not null.
                         */
                        private void setUpMap()
                        {
                            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            mMap.setMyLocationEnabled(true);

                            mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));

                        }

                        private void handleNewLocation(Location location)
                        {
                            Log.d(TAG, location.toString());


                            double currentLatitude = location.getLatitude();
                            double currentLongitude = location.getLongitude();

                            LatLng latLng = new LatLng(currentLatitude, currentLongitude);

                            Toast.makeText(this, "Location Changed " + currentLatitude +" , "
                                    + currentLongitude, Toast.LENGTH_LONG).show();


                            if (mCurrLocationMarker != null)
                            {
                                mCurrLocationMarker.remove();
                            }
                            //mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
                            MarkerOptions options = new MarkerOptions()
                                    .position(latLng)
                                    .title("I am here!");

                            mCurrLocationMarker= mMap.addMarker(options);
                            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                            mMap.animateCamera(CameraUpdateFactory.zoomTo(13));

                        }

                        @Override
                        public void onConnected(Bundle bundle)
                        {
                            Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                            if (location == null)
                            {
                                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
                            }

                            else
                            {
                                handleNewLocation(location);
                            }
                        }

                        @Override
                        public void onConnectionSuspended(int i)
                        {

                        }

                        @Override
                        public void onConnectionFailed(ConnectionResult connectionResult)
                        {
                            /*
                             * Google Play services can resolve some errors it detects.
                             * If the error has a resolution, try sending an Intent to
                             * start a Google Play services activity that can resolve
                             * error.
                             */
                            if (connectionResult.hasResolution()) {
                                try {
                                    // Start an Activity that tries to resolve the error
                                    connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                                    /*
                                     * Thrown if Google Play services canceled the original
                                     * PendingIntent
                                     */
                                } catch (IntentSender.SendIntentException e) {
                                    // Log the error
                                    e.printStackTrace();
                                }
                            }
                            else
                            {
                                /*
                                 * If no resolution is available, display a dialog to the
                                 * user with the error.
                                 */
                                Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
                            }
                        }

                        @Override
                        public void onLocationChanged(Location location)
                        {
                            handleNewLocation(location);
                        }

                        private boolean checkPlayServices()
                        {
                            int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
                            if(resultCode != ConnectionResult.SUCCESS)
                            {
                                if(GooglePlayServicesUtil.isUserRecoverableError(resultCode))
                                {
                                    GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
                                }
                                else
                                {
                                    Toast.makeText(getApplicationContext(), "This device is not supported", Toast.LENGTH_LONG)
                                            .show();
                                    finish();
                                }
                                return false;
                            }
                            return true;
                        }


                        protected synchronized void buildGoogleApiClient()
                        {
                            mGoogleApiClient = new GoogleApiClient.Builder(this)
                                    .addConnectionCallbacks(this)
                                    .addOnConnectionFailedListener(this)
                                    .addApi(LocationServices.API).build();
                        }

                        protected void createLocationRequest()
                        {
                            mLocationRequest = new LocationRequest();
                            mLocationRequest.setInterval(UPDATE_INTERVAL);
                            mLocationRequest.setFastestInterval(FATEST_INTERVAL);
                            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                            mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
                        }

                    }

1 个答案:

答案 0 :(得分:-1)

使用LocationManager并实现LocationListener,更好地聆听位置更改,您不需要GoogleClient来收听位置更新。

要正确收听位置更新,您必须执行以下操作

//Declare a location manager
 private LocationManager locationManager;

//Request location update either by GPS or NETWORK and for accurate results use //GPS

 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 3, this);

//and the new locations will go to the onLocationChanged(Location location) //method that you already overrided

现在停止收听位置更新只需使用此

locationManager.removeUpdates(this);