how to stop receiving location update in google map android -


i making location tracking application. put 2 buttons stop , start, on start button click receiving location update enable, on stop button click stop receiving location update.

but stop receiving location update not working.

                            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 request code send google play services                          * code returned in activity.onactivityresult                          */                         private final static int connection_failure_resolution_request = 9000;                          private googlemap mmap; // might null if google play services apk 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 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 request missing permissions, , overriding                                 //   public void onrequestpermissionsresult(int requestcode, string[] permissions,                                 //                                          int[] grantresults)                                 // handle case user grants permission. see documentation                                 // activitycompat#requestpermissions 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 map if possible (i.e., google play services apk correctly                          * installed) , map has not been instantiated.. ensure ever                          * call {@link #setupmap()} once when {@link #mmap} not null.                          * <p/>                          * if isn't installed {@link supportmapfragment} (and                          * {@link com.google.android.gms.maps.mapview mapview}) show prompt user                          * install/update google play services apk on device.                          * <p/>                          * user can return fragmentactivity after following prompt , correctly                          * installing/updating/enabling google play services. since fragmentactivity may not                          * have been destroyed during process (it                          * stopped or paused), {@link #oncreate(bundle)} may not called again should call                          * method in {@link #onresume()} guarantee called.                          */                         private void setupmapifneeded()                         {                             // null check confirm have not instantiated map.                             if (mmap == null)                             {                                 // try obtain map supportmapfragment.                                 mmap = ((supportmapfragment) getsupportfragmentmanager().findfragmentbyid(r.id.map))                                         .getmap();                                 // check if successful in obtaining map.                                 if (mmap != null)                                 {                                     setupmap();                                 }                             }                         }                          /**                          * can add markers or lines, add listeners or move camera. in case,                          * add marker near africa.                          * <p/>                          * should called once , when sure {@link #mmap} 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 request missing permissions, , overriding                                 //   public void onrequestpermissionsresult(int requestcode, string[] permissions,                                 //                                          int[] grantresults)                                 // handle case user grants permission. see documentation                                 // activitycompat#requestpermissions 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 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 errors detects.                              * if error has resolution, try sending intent                              * start google play services activity can resolve                              * error.                              */                             if (connectionresult.hasresolution()) {                                 try {                                     // start activity tries resolve error                                     connectionresult.startresolutionforresult(this, connection_failure_resolution_request);                                     /*                                      * thrown if google play services canceled original                                      * pendingintent                                      */                                 } catch (intentsender.sendintentexception e) {                                     // log error                                     e.printstacktrace();                                 }                             }                             else                             {                                 /*                                  * if no resolution available, display dialog                                  * user error.                                  */                                 log.i(tag, "location services connection failed 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 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);                         }                      } 

listening location changes better using locationmanager , implementing locationlistener, dont need googleclient listen location updates.

to listen locations update correctly must following

//declare location manager  private locationmanager locationmanager;  //request location update either gps or network , accurate results use //gps   locationmanager.requestlocationupdates(locationmanager.gps_provider, 1000, 3, this);  //and new locations go onlocationchanged(location location) //method overrided 

now stop listening location updates use this

locationmanager.removeupdates(this); 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -