google maps - app takes too long to return longitude and latitude in android -


so code below use obtain longitude , latitude coordinations, however, when run app on android 4.4.3, app takes long bring , obtain coordinates. think result of bad coding ? or should make sure im under direct sky? thank suggestions.

package com.example.geolocation;  import android.app.activity; import android.content.context; import android.location.location; import android.location.locationlistener; import android.location.locationmanager; import android.os.bundle; import android.widget.textview;  public class mainactivity extends activity {      textview textlat;     textview textlong;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);          setcontentview(r.layout.activity_main);          textlat = (textview)findviewbyid(r.id.textlat);         textlong = (textview)findviewbyid(r.id.textlong);          locationmanager lm = (locationmanager)getsystemservice(context.location_service); //gets operating system         locationlistener ll = new mylocationlistener();         lm.requestlocationupdates(locationmanager.gps_provider, 0, 0, ll); //location updated linked          if(lm.isproviderenabled(locationmanager.gps_provider))         {             textlat.settext("gps online (please wait)");             textlong.settext("gps online (please wait)");         }         else          {             textlat.settext("gps offline");             textlong.settext("gps offline");         }          //inner class location listener     }           private class mylocationlistener implements locationlistener{                @override             public void onlocationchanged(location location) {                 // todo auto-generated method stub                 if(location != null)                 {                     double plong = location.getlongitude();                     double plat = location.getlatitude();                      textlat.settext(double.tostring(plat)); //converts values                     textlong.settext(double.tostring(plong));                 }              }              @override             public void onstatuschanged(string provider, int status,                     bundle extras) {                 // todo auto-generated method stub              }              @override             public void onproviderenabled(string provider) {                 // todo auto-generated method stub               }              @override             public void onproviderdisabled(string provider) {                 // todo auto-generated method stub               }          }         } 

just use new api fusedlocationapi getlastlocation , avoid null pointer.

sample code:

public class mapsactivity extends fragmentactivity implements         googleapiclient.connectioncallbacks,         googleapiclient.onconnectionfailedlistener,         locationlistener {      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;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_maps);         setupmapifneeded();          // check if has gps         locationmanager locationmanager = (locationmanager) getsystemservice(context.location_service);         if (!locationmanager.isproviderenabled(locationmanager.gps_provider)) {             buildalertmessagenogps();         }          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(10 * 1000)        // 10 seconds, in milliseconds                 .setfastestinterval(1 * 1000); // 1 second, in milliseconds     }      @override     protected void onresume() {         super.onresume();         setupmapifneeded();         mgoogleapiclient.connect();     }      @override     protected void onpause() {         super.onpause();          if (mgoogleapiclient.isconnected()) {             locationservices.fusedlocationapi.removelocationupdates(mgoogleapiclient, this);             mgoogleapiclient.disconnect();         }     }      /**      * 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() {         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);          //mmap.addmarker(new markeroptions().position(new latlng(currentlatitude, currentlongitude)).title("current location"));         markeroptions options = new markeroptions()                 .position(latlng)                 .title("i here!");         mmap.addmarker(options);         mmap.movecamera(cameraupdatefactory.newlatlng(latlng));     }      @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 void buildalertmessagenogps() {         final alertdialog.builder builder = new alertdialog.builder(this);         builder.setmessage("your gps seems disabled, want enable it?")                 .setcancelable(false)                 .setpositivebutton("yes", new dialoginterface.onclicklistener() {                     public void onclick(@suppresswarnings("unused") final dialoginterface dialog, @suppresswarnings("unused") final int id) {                         startactivity(new intent(android.provider.settings.action_location_source_settings));                     }                 })                 .setnegativebutton("no", new dialoginterface.onclicklistener() {                     public void onclick(final dialoginterface dialog, @suppresswarnings("unused") final int id) {                         dialog.cancel();                     }                 });         final alertdialog alert = builder.create();         alert.show();     } } 

please check here know how use it. , here code(whole project) on github.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -